Javascript res.end不停止脚本的执行
我目前正试图围绕第三方API构建一个API,但在我的Express路线中,我似乎无法让当前脚本停止执行,以下是我的代码:Javascript res.end不停止脚本的执行,javascript,node.js,express,Javascript,Node.js,Express,我目前正试图围绕第三方API构建一个API,但在我的Express路线中,我似乎无法让当前脚本停止执行,以下是我的代码: app.get('/submit/:imei', async function (req, res) { //configure res.setHeader('Content-Type', 'application/json'); MyUserAgent = UserAgent.getRandom(); axios.defaults.withC
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错误,如何停止脚本执行?它也应该有一个成功块
app.get('/submit/:imei',异步函数(req,res){
//配置
res.setHeader('Content-Type','application/json');
MyUserAgent=UserAgent.getRandom();
axios.defaults.withCredentials=true;
const model_info=等待getModelInfo(req.params.imei)
.然后(功能(响应){
返回res.send(JSON.stringify({
"成功":对,,
“res”:回应
}));
})
.catch(函数(错误){
if(error.response&&error.response.status==406){
返回res.send(JSON.stringify({
“成功”:错误,
“原因”:“超出了每天的尝试次数”
}));
}
});
//它将控制台日志
log('即使在406错误之后仍会调用它!');
});代码>如果不希望捕获错误后执行代码,则应执行以下操作:
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'
});
}
}
});
或者,您可以在调用getModelInfo
之后使用then
,并且只有当getModelInfo
没有拒绝时才会调用该代码。您确定它正在命中捕获
或者甚至进入该条件吗?这里甚至没有考虑成功的案例,所以它可能只是在工作,但没有返回任何东西。@我假设浏览器显示JSON响应,那么“停止”脚本是什么意思。它会出现console.log
行,因为您发现了错误。@如果API返回406响应(我试图从中收集数据),我不希望它继续执行脚本?