A Mehmeto
A Mehmeto

Reputation: 1999

Http failure response for http://localhost:3000/api/stuff: 400 Bad Request

I am trying to learn how to save an object into a Mongoose DB. Even though it looks like I have done everything correctly, I keep getting a Http failure response for http://localhost:3000/api/stuff: 400 Bad Request in the browser that shouldn't be there. This error doesn't mean much to me. What's wrong with my request?

I am probably missing something.

app.post('/api/stuff', (req, res, next) => {
    delete req.body._id;
    const thing = new Thing({
        ...req.body
    });
    thing.save()
        .then(() => res.status(201).json({ message: 'Objet enregistré !'}))
        .catch(error => res.status(400).json({ error }));
});

Complete app.js code :

const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const app = express();
const Thing = require('./models/thing');

mongoose.connect(
        'mongodb+srv://username:[email protected]/test?retryWrites=true&w=majority',
        { useNewUrlParser: true, useUnifiedTopology: true }
    ).then(() => console.log('Connexion à MongoDB réussie !'))
    .catch(() => console.log('Connexion à MongoDB échouée !'));

app.use((req, res, next) => {
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader(
        'Access-Control-Allow-Headers',
        'Origin, X-Requested-With, Content, Accept, Content-Type, Authorization'
    );
    res.setHeader(
        'Access-Control-Allow-Methods',
        'GET, POST, PUT, DELETE, PATCH, OPTIONS'
    );
    next();
});

app.use(bodyParser.json());

app.post('/api/stuff', (req, res, next) => {
    delete req.body._id;
    const thing = new Thing({
        ...req.body
    });
    thing.save()
        .then(() => res.status(201).json({ message: 'Objet enregistré !'}))
        .catch(error => res.status(400).json({ error }));
});


app.use('/api/stuff', (req, res) => {
    const stuff = [
        {
            _id: 'oeihfzeoi',
            title: 'Mon premier objet',
            description: 'Les infos de mon premier objet',
            imageUrl: 'https://cdn.pixabay.com/photo/2019/06/11/18/56/camera-4267692_1280.jpg',
            price: 4900,
            userId: 'qsomihvqios',
        },
        {
            _id: 'oeihfzeomoihi',
            title: 'Mon deuxième objet',
            description: 'Les infos de mon deuxième objet',
            imageUrl: 'https://cdn.pixabay.com/photo/2019/06/11/18/56/camera-4267692_1280.jpg',
            price: 2900,
            userId: 'qsomihvqios',
        },
    ];
    res.status(200).json(stuff);
});

module.exports = app;

thing.js :

const mongoose = require('mongoose');

const thingSchema = mongoose.Schema({
    title: { type: String, required: true },
    description: { type: String, required: true },
    imageURL: { type: String, required: true },
    userId: { type: String, required: true },
    price: { type: Number, required: true },
});

module.exports = mongoose.model('Thing', thingSchema);

EDIT :

If I console log req.body and error I get this :

[nodemon] starting `node server.js`
Listening on port 3000
Connexion à MongoDB réussie !
{
  title: 'sadfsaf',
  description: 'sdf fds sag asdf',
  price: 12300,
  imageUrl: 'sadf',
  userId: 'userID40282382'
}
Error [ValidationError]: Thing validation failed: imageURL: Path `imageURL` is required.
    at ValidationError.inspect (/mnt/c/Users/Shadow/Development/scottish_nodejs/backend/node_modules/mongoose/lib/error/validation.js:61:24)
    at formatValue (internal/util/inspect.js:563:31)
    at inspect (internal/util/inspect.js:221:10)
    at formatWithOptions (internal/util/inspect.js:1693:40)
    at Object.Console.<computed> (internal/console/constructor.js:272:10)
    at Object.log (internal/console/constructor.js:282:61)
    at /mnt/c/Users/Shadow/Development/scottish_nodejs/backend/app.js:36:21
    at processTicksAndRejections (internal/process/task_queues.js:93:5) {
  errors: {
    imageURL: MongooseError [ValidatorError]: Path `imageURL` is required.
        at new ValidatorError (/mnt/c/Users/Shadow/Development/scottish_nodejs/backend/node_modules/mongoose/lib/error/validator.js:29:11)
        at validate (/mnt/c/Users/Shadow/Development/scottish_nodejs/backend/node_modules/mongoose/lib/schematype.js:1061:13)
        at /mnt/c/Users/Shadow/Development/scottish_nodejs/backend/node_modules/mongoose/lib/schematype.js:1115:11
        at Array.forEach (<anonymous>)
        at SchemaString.SchemaType.doValidate (/mnt/c/Users/Shadow/Development/scottish_nodejs/backend/node_modules/mongoose/lib/schematype.js:1070:14)
        at /mnt/c/Users/Shadow/Development/scottish_nodejs/backend/node_modules/mongoose/lib/document.js:2303:9
        at processTicksAndRejections (internal/process/task_queues.js:75:11) {
      message: 'Path `imageURL` is required.',
      name: 'ValidatorError',
      properties: [Object],
      kind: 'required',
      path: 'imageURL',
      value: undefined,
      reason: undefined,
      [Symbol(mongoose:validatorError)]: true
    }
  },
  _message: 'Thing validation failed',
  name: 'ValidationError'
}

Upvotes: 1

Views: 11040

Answers (1)

SuleymanSah
SuleymanSah

Reputation: 17858

You have required imageURL field in the schema definition. But in the req.body you use imageUrl, so mongoose gives that error.

If you send your req.body like this, it will work:

{
    "title": "sadfsaf",
    "description": "sdf fds sag asdf",
    "price": 12300,
    "imageURL": "sadf",
    "userId": "userID40282382"
}

Upvotes: 2

Related Questions