gpt4 book ai didi

javascript - 从回调函数内部发送一个值来表达路由器

转载 作者:行者123 更新时间:2023-11-30 20:39:26 25 4
gpt4 key购买 nike

当我从 POST 中保存新作者时,我想返回一条消息,说明新作者已保存。 (如果作者已经存在,我最终也会想要返回一些东西)我遇到的问题是,尽管作者保存在数据库中,但我无法写入 res.locals.messages 来自 author.save() 的回调参数。 (另外,请注意 createAuthor 是一组调用 - 我不确定这是否会使获取 result 的值变得更加困难。)

如何将 result 的值传递给路由器?

路线:

router.post('/', authorController.createAuthor, (req, res) => {
res.json({ messages: res.locals.messages})
})

Controller :

exports.createAuthor = [

check('firstName', 'First name must be specified').isLength({min: 1}).trim(),
check('lastName', 'Last name must be specified').isLength({min: 1}).trim(),
sanitizeBody('firstName').trim().escape(),
sanitizeBody('lastName').trim().escape(),


(req, res, next) => {

const errors = validationResult(req);
var author = new Author({
firstName: req.query.firstName,
lastName: req.query.lastName
});

if (errors.isEmpty()) {

//Edit: added find before save function:
const query = {$or:[{firstName:{$regex: req.query.firstName, $options: 'i'}},
{lastName:{$regex: req.query.lastName, $options: 'i'}}]} //TODO this regex fails if a parameter is missing.

Author.findOne(query).sort([['lastName', 'ascending']]).exec((err, author) => {
if (err) {
return next(err)
}

if(!(author ==null)){
var result = {status: "Author already exists: ", author_id: String(author.id)}
res.locals.messages = result;
next();
}

});


author.save(function (err, newAuthor) {
if (err) {
return next(err)
}

var result = {status: "New author saved", author_id: String(newAuthor.id)}
res.locals.messages = result;

});
}
next();

}
];

最佳答案

在处理保存并设置 res.locals 值后,您需要调用 next :

exports.createAuthor = [

check('firstName', 'First name must be specified').isLength({min: 1}).trim(),
check('lastName', 'Last name must be specified').isLength({min: 1}).trim(),
sanitizeBody('firstName').trim().escape(),
sanitizeBody('lastName').trim().escape(),


(req, res, next) => {

const errors = validationResult(req);
var author = new Author({
firstName: req.query.firstName,
lastName: req.query.lastName
});

if (errors.isEmpty()) {
author.save(function (err, newAuthor) {
if (err) {
return next(err)
}

var result = {status: "New author saved", author_id: String(newAuthor.id)}
res.locals.messages = result;
next();


});
} else {
// Remember to do something about these non-empty errors!
next(new Error('Got more than 0 errors'));
}

}
];

此外,不要忘记处理验证错误数量非零的情况:)

关于javascript - 从回调函数内部发送一个值来表达路由器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49460056/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com