柚子快報(bào)邀請碼778899分享:node.js [ERR
柚子快報(bào)邀請碼778899分享:node.js [ERR
問題描述
如果你的node.js提示:[ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
那么,代表你返回了結(jié)果,但是最后你又不小心再返回了一次。通常是由于方法沒有進(jìn)行等待,或者多條件判斷缺漏造成的。
解決方案:
情況一:返回機(jī)制問題
通過success/error模式來返回結(jié)果,取消最終的默認(rèn)返回;
或者通過await方法返回再return結(jié)果即可。
axios.get(optionsEntitlement.url,{headers,httpsAgent})
// axios.get(optionsEntitlement.url,optionsEntitlement)
.then(function (response) {
// handle success
console.log("entitlement success:"+response);
res.status(200).send(response)
}).catch(function (error) {
// handle error
console.log("entitlement error:"+error);
res.status(500).send({
"message": {
"code": "AIE0001",
"type": "E",
"timestamp": new Date().toISOString(),
"text": "System Unavailable",
error
}
});
});
// res.json({ title: 'LMD GCS Node - entitlement' });
});
情況二:
服務(wù)器會輸出響應(yīng)頭,再輸出主體內(nèi)容,如果你在代碼中設(shè)置了res.writeHead()函數(shù),然后再使用res.send()方法,就會出現(xiàn)這個(gè)錯(cuò)誤。通常要使用res.end()
const body = 'hello https://zhengkai.blog.csdn.net/';
response
.writeHead(200, {
'Content-Length': Buffer.byteLength(body),
'Content-Type': 'text/json;charset=utf-8',
})
.end(body);
認(rèn)識 Express 的 res.send() 和 res.end()
相同點(diǎn)
Express 的 res.end() 和 res.send() 方法的相同點(diǎn):
二者最終都是回歸到?http.ServerResponse.Use?的?response.end()?方法。二者都會結(jié)束當(dāng)前響應(yīng)流程。
不同點(diǎn)
Express 的 res.end() 和 res.send() 方法的不同點(diǎn):
前者只能發(fā)送 string 或者 Buffer 類型,后者可以發(fā)送任何類型數(shù)據(jù)。從語義來看,前者更適合沒有任何響應(yīng)數(shù)據(jù)的場景,而后者更適合于存在響應(yīng)數(shù)據(jù)的場景。
總結(jié)
Express 的 res.end() 和 res.send() 方法使用上,一般建議使用?res.send()方法即可,這樣就不需要關(guān)心響應(yīng)數(shù)據(jù)的格式,因?yàn)?Express 內(nèi)部對數(shù)據(jù)進(jìn)行了處理。
柚子快報(bào)邀請碼778899分享:node.js [ERR
相關(guān)鏈接
本文內(nèi)容根據(jù)網(wǎng)絡(luò)資料整理,出于傳遞更多信息之目的,不代表金鑰匙跨境贊同其觀點(diǎn)和立場。
轉(zhuǎn)載請注明,如有侵權(quán),聯(lián)系刪除。