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



我正在尝试学习如何将对象保存到猫鼬数据库中。尽管看起来我已经正确地完成了所有操作,但我在浏览器中不断收到不应该存在的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 }));
});

完整的应用程序.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:password@cluster0-lrbfc.mongodb.net/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;

事情.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'
}

架构定义中需要imageURL字段。但是在 req.body 中你使用imageUrl,所以猫鼬给出了这个错误。

如果你像这样发送你的 req.body,它将起作用:

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

最新更新