问题描述
我有这个 POST 方法,它使用 FetchURL
中间件从用户提交的 url 中获取数据。
router.post('/',FetchURL,(req,res) => {
console.info('data received');
...
})
当 response.ok
为真时一切正常,但相反的情况并不像预期的那样工作。
我不想在 next
等于 false 时调用 response.ok
。
但我看到“收到的数据”记录到控制台,这意味着下一个函数确实会被自己调用。
fetch_url.js
function FetchURL(req,res,next) {
fetch(req.body.input_url)
.then(response => {
if(response.ok)
return response.json();
// else render error message on the client machine
res.status(response.status)
.render('index',{
errStatus: [response.status,response.statusText]
});
/* Throwing an Error here is the only way I Could prevent the next callback */
// throw new Error(`Request Failed with status code ${response.status}.`);
})
.then(data => {
req.data = data;
next();
})
.catch(err => console.error(err));
}
我在 expressjs 中间件的 documentation 中找不到任何相关内容。我可以防止 next 被调用的唯一方法是在服务器上抛出一个错误。
幕后发生了什么?
解决方法
尝试在 next 调用之前进行第二次检查,如下所示
function FetchURL(req,res,next) {
fetch(req.body.input_url)
.then(response => {
if(response.ok) // wrap your response in a temporary object.
return { fail: false,data: response.json() } ;
// else render error message on the client machine
res.status(response.status)
.render('index',{
errStatus: [response.status,response.statusText]
});
/* Instead of throwing an Error,return something indicating error */
return { fail: true };
})
.then(data => {
// check if previous procedure has failed.
if(!data.fail) {
req.data = data.data;
next();
}
})
.catch(err => console.error(err));
}