title: Express - 400 bad request on POST and PUT
body: <p>I'd like some help as I'm new to Node.js and express. I have the following code which I'm testing on Postman</p>
  
  <pre><code>const Joi = require('@hapi/joi');
  const bodyParser = require('body-parser');
  
  // Load the express framework
  const express = require('express');
  const app = express();
  
  app.use(express.json());
  app.use(bodyParser.json());
  app.use(express.urlencoded({ extended: true }));
  
  // temp array
  const courses = [
      {id: 1, title: 'Learning Node.js'},
      {id: 2, title: 'How to become a full stack dev'},
      {id: 3, title: 'Master your Javascript skills'}
  ];
  app.post('/api/courses', (request, response) =&gt; {
      let error = validateCourse(request.body);
      if (error) {
          response.status(400).send(error.details[0].message); // *
          return;
      }
  
      let course = {
          id: courses.length + 1,
          name: request.body.name
      };
  
      // TODO save
      console.log('TODO save the record');
  
      response.send(course);
  });
  
  app.put('/api/courses/:id', (request, response) =&gt; {
      let course = courses.find(c =&gt; c.id === parseInt(request.params.id));
      if(!course) response.status(404).send('Oops!');
  
      let { error } = validateCourse(request.body);
      if (error) {
          response.status(400).send(error.details[0].message);
          return;
      }
  
      // TODO save
      console.log('TODO save the record');
  
      response.send(course);
  });
  
  
  function validateCourse(course) {
      let schema = Joi.object({
          name: Joi.string().min(4).required()
      });
      console.log(course);
      return schema.validate(course);
  }
  </code></pre>
  
  <p>Either when I make a PUT or a POST request in which I supply a <code>name</code> (i.e the validation should pass) I get a 400 error. </p>
  
  <p>On POST request I see the following in the console which refers to where my asterisk (*) is</p>
  
  <pre><code>TypeError: Cannot read property '0' of undefined
      at /app/index.js:50:48
  </code></pre>
  
  <p>On PUT request I see the following in the console <code>Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client</code></p>
  
  <p>In both cases the console.log I have in the validateCourse function is showing an empty object <code>{}</code></p>
  
  <p>This is a screenshot from postman
  <a href="https://i.stack.imgur.com/a9CNs.png" rel="noreferrer"><img src="https://i.stack.imgur.com/a9CNs.png" alt="enter image description here"></a></p>
  
  <p>Any ideas what I'm doing wrong?</p>