只是想問


到達入口點后,我收到了此錯誤訊息
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at new NodeError (node:internal/errors:372:5)
at ServerResponse.setHeader (node:_http_outgoing:576:11)
at ServerResponse.header (C:\Users\mmeeee\Desktop\REACT_APP\node_modules\express\lib\response.js:794:10)
at ServerResponse.send (C:\Users\mmeeee\Desktop\REACT_APP\node_modules\express\lib\response.js:174:12)
at ServerResponse.json (C:\Users\mmeeee\Desktop\REACT_APP\node_modules\express\lib\response.js:278:15)
at C:\Users\mmeeee\Desktop\REACT_APP\backend\controllers\userController.js:27:9
at processTicksAndRejections (node:internal/process/task_queues:96:5)
我試圖用 res.end 替換 res.json ,但這似乎不是問題所在。
uj5u.com熱心網友回復:
在該protected中間件中,您正在呼叫塊next中的 ,這可能會產生向客戶端發送回應的副作用try。您還將回應發送到catch塊中的客戶端。在這些塊中的任何一個執行之后,您不應該嘗試進一步修改回應,如果您最終沒有token. 潛在的重構:
if (
req.headers.authorization &&
req.headers.authorization.startsWith("Bearer")
) {
try {
const token = req.headers.authorization.split(" ")[1];
if (!token) throw 'No token!'
const decoded = theCodeYouWrote(token);
req.user = await theCodeYouWroteForTheUser(decoded);
} catch (error) {
console.error(error);
res.status(401).json(...);
return;
}
}
next();
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/528156.html
