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-pars
Solution 1:
👨🏫 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 saveconsole.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 saveconsole.log('TODO save the record');
response.send(course);
});
functionvalidateCourse(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 🙏.
Solution 2:
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.
Post a Comment for "Express - 400 Bad Request On Post And Put"