Create a Node.js Express application with two endpoints: one to accept JSON input containing an array of numbers and return their sum, and another endpoint to accept a string and return its length. The application should include proper error handling and validation for the input data.
PLAINFORMAT
const express = require('express');
const app = express();
const port = process.env.PORT || 3000;

app.use(express.json());

// Endpoint to accept JSON input containing an array of numbers and return their sum
app.post('/sum', (req, res) => {
  const numbers = req.body.numbers;

  if (!Array.isArray(numbers)) {
    return res.status(400).json({ error: 'Input must be an array of numbers.' });
  }

  const sum = numbers.reduce((accumulator, currentValue) => {
    if (typeof currentValue !== 'number') {
      throw new Error('All elements in the array must be numbers.');
    }
    return accumulator + currentValue;
  }, 0);

  res.json({ sum });
});

// Endpoint to accept a string and return its length
app.post('/length', (req, res) => {
  const inputString = req.body.inputString;

  if (typeof inputString !== 'string') {
    return res.status(400).json({ error: 'Input must be a string.' });
  }

  const length = inputString.length;
  res.json({ length });
});

// Error handling middleware
app.use((err, req, res, next) => {
  if (res.headersSent) {
    return next(err);
  }
  res.status(400).json({ error: err.message });
});

// Start the server
app.listen(port, () => {
  console.log(`Server running at http://localhost:${port}`);
});