Javascript 为何拒绝未经处理的承诺
无论我在哪里使用postman向Javascript 为何拒绝未经处理的承诺,javascript,node.js,mongodb,Javascript,Node.js,Mongodb,无论我在哪里使用postman向localhost:5000/api/profile/experience发出post请求,我都会收到这些警告 UnhandledPromiseRejectionWarning: ValidationError: Profile validation failed: experience.0.title: Path `title` is required., experience.0.company: Path `company` is required., ex
localhost:5000/api/profile/experience
发出post请求,我都会收到这些警告
UnhandledPromiseRejectionWarning: ValidationError: Profile validation failed: experience.0.title: Path `title` is required., experience.0.company: Path `company` is required., experience.0.from: Path `from` is required.
而且我并没有收到错误消息,说标题、公司、from值是必需的,即使我并没有输入这些字段。
这里是我的验证js文件
const Validator = require('validator');
const isEmpty = require('./is-empty');
module.exports = function validateExperienceInput(data){
let errors = {};
data.title = !isEmpty(data.title) ? data.title : '';
data.company = !isEmpty(data.company) ? data.company : '';
data.from = !isEmpty(data.from) ? data.from : '';
if(Validator.isEmpty(data.title)){
errors.title = 'Title field is required'
}
if(Validator.isEmpty(data.company)){
errors.company = 'company field is required'
}
if(Validator.isEmpty(data.from)){
errors.from = 'From field is required'
}
return {
errors,
isValid: isEmpty(errors)
}
}
这是路由器文件
router.post('/experience', passport.authenticate('jwt',{session: false}), (req,res) => {
const {errors, isValid} = validateExperienceInput(req.body);
Profile.findOne({user:req.user.id})
.then(profile => {
const newExp = {
title: req.body.title,
company: req.body.company,
location: req.body.location,
from: req.body.from,
to: req.body.to,
current: req.body.current,
description: req.body.description
}
// Add to exp array
profile.experience.unshift(newExp)
profile.save().then(profile => res.json(profile))
})
})
我遗漏了什么?您需要在
findOne()
中添加一个catch()
(拒绝处理程序)来处理findOne()
中发生的任何错误/拒绝。从Node.js流程文档中可以看到:
每当发出承诺时,就会发出“unhandledRejection”事件
拒绝,且在回合内承诺未附加任何错误处理程序
事件循环的一部分。当使用承诺编程时,例外情况是
概括为“拒绝承诺”。拒绝可以被抓到并且
使用promise.catch()进行处理,并通过promise进行传播
链条“unhandledRejection”事件可用于检测和
跟踪被拒绝但未被拒绝的承诺
但这一问题尚未得到解决
基本上,只要有一个then()
,就可以添加一个catch()
,以处理任何错误和拒绝
希望这有帮助
router.post(
"/experience",
passport.authenticate("jwt", { session: false }),
(req, res) => {
const { errors, isValid } = validateExperienceInput(req.body);
Profile.findOne({ user: req.user.id })
.then(profile => {
const newExp = {
title: req.body.title,
company: req.body.company,
location: req.body.location,
from: req.body.from,
to: req.body.to,
current: req.body.current,
description: req.body.description
};
// Add to exp array
profile.experience.unshift(newExp);
profile.save().then(profile => res.json(profile));
})
.catch(err => {
// do something with error here such send error message or logging
// res.json(err);
});
}
);