如何解决回调函数“next”自动执行,无需调用
我有这个 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));
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。