我正在使用request软件包,它可以工作,但是在执行请求并将状态代码发送给用户之后,即使我使用return,它仍继续执行代码。这是我的代码
request(longurl, {method: 'HEAD'}, function(error,response,body){
if(error){
return res.status(409).send({
message: 'URL is not valid'
})
}
})
if(other_condition){
return res.status(409).send({})
}
它给了我
(节点:3040)UnhandledPromiseRejectionWarning:错误:无法设置标题 在发送之后。
答案 0 :(得分:2)
问题是您正在回调函数中调用return
。这使该函数返回,但是外部函数将继续执行。也许您的other_condition检查应该在回调内部,然后您就不需要return语句。
request(longurl, {method: 'HEAD'}, function(error,response,body){
if(error){
res.status(409).send({
message: 'URL is not valid'
})
} else if(other_condition){
res.status(409).send({})
}
})