res.end 不停止脚本执行

我目前正在尝试围绕第 3 方 API 构建 API,但是在我的 Express 路由中,我似乎无法让当前脚本停止执行,这是我的代码:


app.get('/submit/:imei', async function (req, res) {

    //configure

    res.setHeader('Content-Type', 'application/json');

    MyUserAgent = UserAgent.getRandom();

    axios.defaults.withCredentials = true;


    const model_info = await getModelInfo(req.params.imei).catch(function (error) {

        if(error.response && error.response.status === 406) {

            return res.send(JSON.stringify({

                'success': false,

                'reason': 'exceeded_daily_attempts'

            }));

        }

    });



    console.log('This still gets called even after 406 error!');

});

如果初始请求返回406错误,如何停止执行脚本?


侃侃尔雅
浏览 68回答 2
2回答

慕的地6264312

如果您不想在捕获错误后执行代码,那么您应该这样做:app.get('/submit/:imei', async function (req, res) {    //configure    res.setHeader('Content-Type', 'application/json');    MyUserAgent = UserAgent.getRandom();    axios.defaults.withCredentials = true;    try {        const model_info = await getModelInfo(req.params.imei);            console.log('This will not get called if there is an error in getModelInfo');        res.send({ success: true });    } catch(error) {        if(error.response && error.response.status === 406) {            return res.send({                'success': false,                'reason': 'exceeded_daily_attempts'            });        }    }});或者,您可以在通话then后使用,只有在不拒绝getModelInfo时才会调用该代码。getModelInfo

九州编程

它也应该有一个成功块。app.get('/submit/:imei', async function (req, res) {    //configure    res.setHeader('Content-Type', 'application/json');    MyUserAgent = UserAgent.getRandom();    axios.defaults.withCredentials = true;    const model_info = await getModelInfo(req.params.imei)        .then(function (response) {            return res.send(JSON.stringify({                'success': true,                'res': response            }));        })        .catch(function (error) {            if (error.response && error.response.status === 406) {                return res.send(JSON.stringify({                    'success': false,                    'reason': 'exceeded_daily_attempts'                }));            }        });    //it will console log    console.log('This still gets called even after 406 error!');});
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript