gpt4 book ai didi

node.js - 如何获取错误: Cannot set headers after they are sent to the client is thrown?所在的行

转载 作者:太空宇宙 更新时间:2023-11-03 22:04:50 30 4
gpt4 key购买 nike

由于我对 Node 还很陌生,所以我不知道如何调试我的代码。在 c++ 或 python 等编码语言中,我们的编译器会告诉我们错误所在的行

例如:

    print("Hello World")    a===a

This will result in an error like:

'File "main.py", line 2                                                                                                       
a===a
^
SyntaxError: invalid syntax'

但是在 Node 中我得到了错误的行数,就像本例一样:

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the clientat ServerResponse.setHeader (_http_outgoing.js:455:11)at ServerResponse.header (D:\Node-Tries\22-07-19 to 26-07-19\node_modules\express\lib\response.js:771:10)at ServerResponse.send (D:\Node-Tries\22-07-19 to 26-07-19\node_modules\express\lib\response.js:170:12)at done (D:\Node-Tries\22-07-19 to 26-07-19\node_modules\express\lib\response.js:1008:10)at tryHandleCache (D:\Node-Tries\22-07-19 to 26-07-19\node_modules\ejs\lib\ejs.js:260:5)at View.exports.renderFile [as engine] (D:\Node-Tries\22-07-19 to 26-07-19\node_modules\ejs\lib\ejs.js:485:10)at View.render (D:\Node-Tries\22-07-19 to 26-07-19\node_modules\express\lib\view.js:135:8)at tryRender (D:\Node-Tries\22-07-19 to 26-07-19\node_modules\express\lib\application.js:640:10)at Function.render (D:\Node-Tries\22-07-19 to 26-07-19\node_modules\express\lib\application.js:592:3)at ServerResponse.render (D:\Node-Tries\22-07-19 to 26-07-19\node_modules\express\lib\response.js:1012:7)

我读了一些关于此错误的帖子,据我所知,如果我在发送 header 正文信息后尝试发送 setheader 信息,就会发生这种情况吗?我主要在程序中使用 res.render 和 res.end,那么有没有办法调试进行额外调用的确切行?

最佳答案

将此代码放在您的代码之上

Object.defineProperty(global, '__line', {
get: function(){
return ((new Error()).stack.split("\n")[2].trim().replace(/^(at\s?)(.*)/gim, "$2 >").replace(__dirname, ""))
}
})

然后使用console.log,例如:

console.log(__line, "somthing");

它将显示行号和日志

关于node.js - 如何获取错误: Cannot set headers after they are sent to the client is thrown?所在的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57218821/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com