[http:// localhost:3000 / api / stuff的HTTP失败响应:400错误的请求

问题描述 投票:1回答:1

我正在尝试学习如何将对象保存到Mongoose数据库中。即使看起来我已正确完成所有操作,但我仍在浏览器中收到不应该出现的Http failure response for http://localhost:3000/api/stuff: 400 Bad Request。这个错误对我来说意义不大。我的请求出了什么问题?

我可能缺少一些东西。

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.js代码:

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

编辑:

如果我控制台登录req.bodyerror,我会得到这个:

[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'
}
node.js mongodb express mongoose
1个回答
0
投票

您在模式定义中需要imageURL字段。但是在req.body中,您使用imageUrl,所以猫鼬会给出该错误。

如果您以这种方式发送您的需求方,它将起作用:

{
    "title": "sadfsaf",
    "description": "sdf fds sag asdf",
    "price": 12300,
    "imageURL": "sadf",
    "userId": "userID40282382"
}
© www.soinside.com 2019 - 2024. All rights reserved.