简体   繁体   English

错误 [ERR_HTTP_HEADERS_SENT]:在向客户端发出请求时无法设置标头,当向 API 发出请求时

[英]Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client, when making request to API

I keep getting this error in my terminal after I make a request to the API向 API 发出请求后,我的终端中不断出现此错误

[ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at ServerResponse.setHeader (_http_outgoing.js:518:11)
    at ServerResponse.header (D:\GitHub\Obsidion-Dashboard\node_modules\express\lib\response.js:771:10)
    at ServerResponse.send (D:\GitHub\Obsidion-Dashboard\node_modules\express\lib\response.js:170:12)
    at ServerResponse.json (D:\GitHub\Obsidion-Dashboard\node_modules\express\lib\response.js:267:15)
    at D:\GitHub\Obsidion-Dashboard\api\database.js:169:36
    at processTicksAndRejections (internal/process/task_queues.js:97:5) {
  code: 'ERR_HTTP_HEADERS_SENT'
}

My router looks like this我的路由器长这样

router.get('/prefix', (req, res) => {
    if (!req.query.token) throw new Error('NoTokenProvided');
    if (!req.query.guildid) throw new Error('NoGuildIDProvided');
    const token = req.query.token;
    const guildid = req.query.guildid;

    var sql = `SELECT token FROM auth WHERE token='${token}'`;

    db.all(sql, [], (err, rows) => {
        if (err) {
            throw new Error("ErrorWithDatabase");
        }

        if (rows.length === 0) {
            res.json({code: 401, "message": "That is not a valid token."})
        }

        rows.forEach((row) => {
            if (row.token === token) {
                pool.query(`SELECT prefix FROM guild WHERE id='${guildid}'`)
                .then(response => {
                    // console.log(response.rows[0].prefix)
                    if (!response.rows[0]) {
                        return res.json({code: 200, "message": "User has not setup a custom prefix."})
                    } else {
                        return res.json({code: 200, "prefix": response.rows[0].prefix})
                    }
                })
                .catch(e => console.error(e))
            } else {
                res.json({code: 401, "message": "That is not a valid token."})
            }
        })

    });
})

It shouldn't be trying to send headers to the router after I have returned res.json.在我返回 res.json 后,它不应该尝试将标头发送到路由器。 It is connecting to a postgresql database, and seems to be connecting to it just fine.它正在连接到 postgresql 数据库,并且似乎可以很好地连接到它。

You are attempting to send a response inside a .forEach() which means you will be trying to send more than one response per request.您正在尝试在.forEach()中发送响应,这意味着您将尝试在每个请求中发送多个响应。 Can't do that.不能那样做。 You get to send one response for each incoming request.您可以为每个传入请求发送一个响应。

If you want to just send the first response that matches, then change your .forEach() to a regular for loop and then when you return, it will terminate the loop.如果您只想发送匹配的第一个响应,则将.forEach()更改为常规for循环,然后当您返回时,它将终止循环。

If you want to send multiple responses, then what you need to do is to collect all the results into a local array and then send them all at the end.如果要发送多个响应,那么您需要做的是将所有结果收集到一个本地数组中,然后在最后将它们全部发送出去。 And, since you're using asynchronous operations inside the loop, you will either have to use await to pause the loop or use Promise.all() to collect all the asynchronous results and to know when they are all done.而且,由于您在循环内使用异步操作,您将不得不使用await暂停循环或使用Promise.all()收集所有异步结果并知道它们何时完成。


FYI, in these days of asynchronous programming and block scoped variables, I would just about consider .forEach() to be obsolete because a for loop is superior in every way.仅供参考,在异步编程和块范围变量的这些日子里,我只是认为.forEach()已过时,因为for循环在各方面都优越。 It has the ability to use await and actually suspend the loop and it has superior flow control since you can break , continue or return - none of which you can do with .forEach() .它能够使用await并实际暂停循环,并且它具有出色的流量控制,因为您可以breakcontinuereturn - 这些都不能用.forEach()来完成。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 错误 [ERR_HTTP_HEADERS_SENT]:将标头发送到客户端后无法设置标头 POST HTTP REQUEST - Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client POST HTTP REQUEST 错误[ERR_HTTP_HEADERS_SENT]:将标头发送到客户端后无法设置标头-Express + Request - Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client - Express + Request 发布请求:错误 [ERR_HTTP_HEADERS_SENT]:发送到客户端后无法设置标头 - Post request: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client API 错误 [ERR_HTTP_HEADERS_SENT]: 发送到客户端后无法设置标头 - API Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client 尝试重定向时出现“错误 [ERR_HTTP_HEADERS_SENT]:在将标头发送到客户端后无法设置标头” - Getting “Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client” when trying to redirect 登录时出现错误 [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client - When loging in I get Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client 错误说明:错误 [ERR_HTTP_HEADERS_SENT]:在尝试创建登录 api 时无法设置标头后发送到客户端 - Error stating: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client when trying to create a login api ErrorCaptureStackTrace(错误); ^ 错误 [ERR_HTTP_HEADERS_SENT]:将标头发送到客户端后无法设置标头 - ErrorCaptureStackTrace(err); ^ Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client 我的错误是:错误[ERR_HTTP_HEADERS_SENT]:无法在将标头发送到客户端后设置标头 - My error is: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client ExpressJS - 未处理的拒绝错误:错误 [ERR_HTTP_HEADERS_SENT]:发送到客户端后无法设置标头 - ExpressJS - Unhandled rejection Error: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM