当用户不是管理员时,我有一个错误,它不显示我的消息"未被授权访问此页面";因为我在控制台中得到了这个错误:
TypeError: productController.createProduct(...).then is not a function
我有一个这样设置的路由器:
router.post('/create',auth.verify, (req, res)=>{
const isAdmin = auth.decode(req.headers.authorization).isAdmin;
productController.createProduct(req.body,isAdmin).then(result => res.send(result));})
我的控制器:
module.exports.createProduct = (reqBody, isAdmin) => {
if (isAdmin === true) {
let newProduct = new Product({
name: reqBody.name,
description: reqBody.description,
price: reqBody.price,
});
return newProduct.save().then((result, error) => {
return error ? false : 'Successfully created a product';
});
} else {
return 'Not authorized to access this page';
}
};
当用户是管理员时,一切工作正常。我想知道这是否与我如何在用户不是管理员时返回我的消息有关。因为我在使用承诺?
基本上有两种方法可以解决这个问题。
在第一种方法中,您可以解决API的总体设计并使代码更有效
例如,如果根据user
是否为admin
,操作成功,则可以响应Promise。reject或Promise.resolve。但是,如果你返回一个Promise。从createProduct
函数中拒绝,那么你也应该更新你在控制器中处理拒绝的方式。
例如:
createProduct.js
module.exports.createProduct = (reqBody, isAdmin) => {
if (isAdmin === true) {
let newProduct = new Product({
name: reqBody.name,
description: reqBody.description,
price: reqBody.price,
});
return newProduct.save().then((result, error) => {
return error ? false : 'Successfully created a product';
});
} else {
// Return a promise here
return Promise.reject('Not authorized to access this page');
}
};
controller.js
router.post('/create',auth.verify, (req, res)=>{
const isAdmin = auth.decode(req.headers.authorization).isAdmin;
productController.createProduct(req.body,isAdmin)
.then(result => res.send(result))
.catch(error => res.send(error)); // catch will be executed due to Promise.reject
})
或者,以第二种方式,您可以简单地从createProduct函数的else块返回Promise.resolve
。
的例子:
return Promise.resolve("Not authorized to access this page")
在这种情况下,你不需要更新你的控制器代码。
我建议遵循。then .catch方式来处理事情,以便捕获您在产品创建部分可能遇到的任何错误。它使错误跟踪更容易。
你需要在成功和错误的情况下返回一个承诺:
module.exports.createProduct = (reqBody, isAdmin) => {
if (isAdmin === true) {
let newProduct = new Product({
name: reqBody.name,
description: reqBody.description,
price: reqBody.price,
});
return newProduct.save().then((result, error) => {
return error ? false : 'Successfully created a product';
});
} else {
// Return a promise here
return Promise.reject('Not authorized to access this page');
}
};
你是正确的,如果用户不是管理员,它将不起作用,你需要返回一个承诺。最简单的解决方案是将else语句修改如下:
else{
return Promise.resolve("Not authorized to access this page")
}
您还可以返回Promise.reject(new Error("Not authorized to access this page"))
,这将强制任何使用此函数的程序处理此场景的错误。这可能适合你的设计,也可能不适合。