我不明白为什么错误发送后无法设置标题。。 这是我的错误。
_http_outgoing.js:494
throw new Error('Can\'t set headers after they are sent.');
^
Error: Can't set headers after they are sent.
at validateHeader (_http_outgoing.js:494:11)
at ServerResponse.setHeader (_http_outgoing.js:501:3)
at ServerResponse.header (D:\trraks\node_modules\express\lib\response.js:767:10)
at ServerResponse.send (D:\trraks\node_modules\express\lib\response.js:170:12)
at ServerResponse.json (D:\trraks\node_modules\express\lib\response.js:267:15)
at IncomingMessage.<anonymous> (D:\trraks\app\routes\api.js:58:17)
at emitOne (events.js:116:13)
at IncomingMessage.emit (events.js:211:7)
at IncomingMessage.Readable.read (_stream_readable.js:475:10)
at flow (_stream_readable.js:846:34)
at resume_ (_stream_readable.js:828:3)
at _combinedTickCallback (internal/process/next_tick.js:138:11)
at process._tickCallback (internal/process/next_tick.js:180:9)
我正在尝试通过用户手机号码发送OTP,这是所有的声明
var code = user.CODE;
var msg =urlencode("Dear User,\nVerify your mobile number.\nYour verification code is "+ code);
var number=user.MOBILENO;
var data ='username='+username+'&hash='+hash+'&sender='+sender+'&numbers='+number+'&message='+msg
var options = {
host: 'api.textlocal.in',
path: '/send?'+data
};
callback = function(response)
{
response.on('data', function (chunk)
{
res.json({ success: true, messege: "Messege send on given number"});
});
}
第一次运行代码后,一切正常,但第二次运行,则显示上述错误。
http.request(options,callback).end();
以上行发送味精。
Verifyotp.GetMobileNumber(user.MOBILENO,function(err,mobexits){
if (!mobexits) {
// new number with new OTP
user.save(function(err){
if(err){
// console.log(err);
res.json({success:false, messege:"Something went wrong while trying to send otp"});
}else{
res.json({success:true, messege: "OTP sent on given mobile number new"});
http.request(options, callback).end();
}
})
}else{
// updating new OTP on old number
Verifyotp.UpdateOtp(user.MOBILENO,user.CODE,function(err,update){
if (!update) {
res.json({success:false, messege: "something went wrong while sending OTP"})
}else{
res.json({success:true, messege: "OTP sent on given mobile number updated"});
http.request(options, callback).end();
}
});
}
});
这是我的mongooseSchema:
var User = module.exports = mongoose.model('verifydata',UserSchema);
module.exports.GetMobileNumber = function(mobileno,callback){
const query={MOBILENO:mobileno};
User.findOne(query,callback);
}
module.exports.UpdateOtp = function(mobilenumber,code,callback){
const query = {MOBILENO: mobilenumber};
User.findOneAndUpdate(query, { CODE: code }, callback);
}
帮帮我的朋友们……我尝试了一切,但没有任何效果。 谢谢。
答案 0 :(得分:0)
免责声明,我没有彻底检查您的代码,我发现一个建议是,在理想情况下,您不要在函数中多次使用“ res.send”或相关代码。当您尝试多次发送响应时,通常会引发该错误。因此,为了安全起见,请尝试只使用一次,或最多两次使用res(首先用于发送响应,其次用于引发错误)