我正在学习快速、节点和Mongoose的ScotchIO教程--我似乎不能让req.body通过。
如果我在Postman中发出请求,它工作正常-我可以在Mlab上看到记录更新:-


但是如果我在chrome中发出一个fetch() POST请求(在那里进行测试,直到我可以让它工作,然后我会转到一个React Native应用程序),我会得到一系列的ValidationError: User validation failed (用户是我的模式,然后它会变得更具体,比如ValidatorError: Path,userName,is required.等等)。
fetch('http://localhost:3001/api/users', {
method: 'POST',
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
body: {
userName: 'IngleburtHumperdink',
email: "Ingle@Humber.com",
password: "mypw_blah"
}
})我的方案:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const UserSchema = new Schema({
userName: {
type: String,
required: true,
},
email: {
type: String,
required: true,
},
password: {
type: String,
required: true,
}
});
module.exports = mongoose.model('User', UserSchema);更新: server.js

发布于 2018-07-23 23:32:23
结果我错过了body: JSON.stringify({ userName:'myUserName' })。
所以你是对的@AlexBlex,我发送的是JSON,只是需要json.stringify()来转换它。
经过测试和修复。非常感谢两位!
https://stackoverflow.com/questions/51481242
复制相似问题