简体   繁体   中英

Express - 400 bad request on POST and PUT

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

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) => {
    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) => {
    let course = courses.find(c => 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);
}

Either when I make a PUT or a POST request in which I supply a name (ie the validation should pass) I get a 400 error.

On POST request I see the following in the console which refers to where my asterisk (*) is

TypeError: Cannot read property '0' of undefined
    at /app/index.js:50:48

On PUT request I see the following in the console Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

In both cases the console.log I have in the validateCourse function is showing an empty object {}

This is a screenshot from postman在此处输入图片说明

Any ideas what I'm doing wrong?

👨‍🏫 I've been test this code and I mean you can try this code below 👇:

app.post('/api/courses', (request, response) => {
  let { error } = validateCourse(request.body);

  if (error) {
      response.status(400).send(error.details[0].message); // *
  }

  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) => {
  let course = courses.find(c => 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);
  }

  // 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);
}

I hope it's can help you 🙏.

let course = courses.find(c => c.id === parseInt(request.params.id))
if(!course) return response.status(404).send('Oops!');

let { error } = validateCourse(request.body);
if (error) {
    return response.status(400).send(error.details[0].message);
}

response.send(course);

This must resolve the error that you are getting on PUT request.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM