回调函数 'next' 自动执行,无需调用它

Callback function 'next' is executed automatically without making a call to it

我有这个 POST 方法,它使用 FetchURL 中间件从用户提交的 url 中获取数据。

router.post('/', FetchURL, (req, res) => {

    console.info('data received');
    ...
})

response.ok 为真时一切正常,但相反的情况并不像预期的那样有效。 我不希望 nextresponse.ok 等于 false 时被调用。

但我看到“收到数据”记录到控制台,这意味着下一个函数确实会自行调用。

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));
}