收到的错误消息是:
"User validation failed: email: Path
display_name
is required."
发回的错误名称是:ValidationError。
ajax调用的代码是:
function submit_new_user(display_name, email, password){
let user_data = new New_User(display_name, email, password);
console.log(user_data);
$.ajax ({
dataType: 'JSON',
data: user_data,
method:'POST',
url: 'http://localhost:3001/user',
success: (res)=>{
console.log(res);
},
error: (xhr, ajaxOptions, thrownError)=>{
console.log(xhr, ajaxOptions, thrownError);
}
});
};
上面看到的console.log打印:
New_User {display_name: "test", email: "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d6a2b3a5a296a2b3a5a2f8b5b9bb" rel="noreferrer noopener nofollow">[email protected]</a>", password: "Passw0rd"}
服务器路由是:
app.post('/user', (req, res)=>{
let body = _.pick(req.body, ['display_name', 'email', 'password']);
let user = new User(body);
user.save().then(()=>{
return user.generateAuthToken();
}).then((token)=>{
res.header('x-auth', token).send(user);
}).catch((err)=>{
res.status(400).send(err);
});
});
当使用 Postman 执行 ping 操作时,此路由有效。服务器支持cors。
模型如下:
var UserSchema = new mongoose.Schema({
display_name: {
type: String,
unique: true,
required: true,
validate: {
validator: (val)=>{
return /^[\w\s]+$/.test(val);
},
message: '{VALUE} is not a valid display name. Only
alphanumeric, upper and lower case characters are allowed.'
}
},
email: {
type: String,
required: true,
unique: true,
validate: {
validator: validator.isEmail,
message: '{VALUE} is not a valid email.'
}
},
password: {
type: String,
require: true,
minlength: 6
},
tokens: [{
access:{
type: String,
required: true
},
token: {
type: String,
required: true
}
}]
});
我还在学习node.js。我在指导下完成了 API 的创建,并尝试自己构建一个前端。
离开的对象包含三个值对 - 但到达的对象在服务器更改之前是空的。我不知道为什么。
最佳答案
解决方案:问题出在服务器端 bodyParser 中。我忘记包含编码的 url 方法。它不会解析传入的 JSON,因为之前仅使用 Postman 测试了 API,因此无需使用 .urlencoded() 方法。
关于javascript - Node.js/Mongoose/lodash - 服务器响应 : User Validation Failed: path `foo` is required,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46186031/