我有一個 nodejs react 應用程式,我在其中獲取一些資料到服務器:
await fetch(`${process.env.NEXT_PUBLIC_DR_HOST}/validate`, {
method: 'POST',
body: valBody,
headers: { 'Content-Type': 'application/json' }
})
之后,將驗證資料以查看其內容中是否存在任何錯誤。如果一切正常,會回傳 200 狀態碼(手動或默認)作為回應,然后會發生其他事情:
.then(res =>
{
console.log(res)
if (res.status === 200)
{
//do stuff
如果有錯誤,將發送 400 代碼
if (error)
{
const msg = error.details.map(e => e.message).join(',') //
res.status(400).send("Invalid Data")
throw new ServerError("Invalid Data", 400)
}
僅發送res.status(400)而不發送 .send 只會回傳 200 res。一切正常,但拋出錯誤:Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client. 發生這種情況只是因為我在 status code 之后發送了一條訊息res.status(400).send("Invalid Data"),但正如我所說,僅回傳一個 status coderes.status(400)不會影響將其保留為 200 的回應狀態。我該怎么辦?
uj5u.com熱心網友回復:
也有可能
throw new ServerError("Invalid Data", 400)
導致問題。請求處理程式中的同步例外將被 express 捕獲,它會嘗試發送錯誤回應,但您已經完成了
res.status(400).send(...)
因此,洗掉throw new ServerError("Invalid Data", 400)或res.status(400).send("Invalid Data")。兩者都不要。這是一個猜測,我們需要查看整個請求處理程式才能確定要建議什么。而且,根據代碼的結構,您可能還需要 areturn來阻止任何其他代碼路徑執行。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/442619.html
