【发布时间】:2021-05-16 21:38:14
【问题描述】:
我有这个 POST 方法,它使用 FetchURL 中间件从用户提交的 url 中获取数据。
router.post('/', FetchURL, (req, res) => {
console.info('data received');
...
})
response.ok 为 true 时一切正常,但相反的情况并不完全符合预期。
我不希望在 response.ok 等于 false 时调用 next。
但是我看到“data received”记录到控制台,这意味着下一个函数确实被自己调用了。
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 被调用的唯一方法是在服务器上抛出一个错误。
这里的幕后发生了什么?
【问题讨论】:
标签: express ejs middleware node-fetch