node.js - 错误 [ERR_HTTP_HEADERS_SENT] : Cannot set headers after they are sent to the client - Express + Request

标签 node.js express

我知道这是一个非常基本的问题,但我发现自己花了太多时间来理解为什么会发生这种情况。

下面是我使用 npm request lib 来查询 api 并使用快速响应发送响应的 api。当我点击这个时,我得到:

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at ServerResponse.setHeader (_http_outgoing.js:470:11)
    at ServerResponse.header (C:\Users\GayathriGanesan\Documents\sampleNode\node_modules\express\lib\response.js:767:10)
    at ServerResponse.send (C:\Users\GayathriGanesan\Documents\sampleNode\node_modules\express\lib\response.js:170:12)
    at ServerResponse.json (C:\Users\GayathriGanesan\Documents\sampleNode\node_modules\express\lib\response.js:267:15)
    at Request._callback (C:\Users\GayathriGanesan\Documents\sampleNode\app.js:80:34)
    at Request.self.callback (C:\Users\GayathriGanesan\Documents\sampleNode\node_modules\request\request.js:185:22)
    at Request.emit (events.js:189:13)
    at Request.<anonymous> (C:\Users\GayathriGanesan\Documents\sampleNode\node_modules\request\request.js:1161:10)
    at Request.emit (events.js:189:13)
    at IncomingMessage.<anonymous> (C:\Users\GayathriGanesan\Documents\sampleNode\node_modules\request\request.js:1083:12)

下面是编写的代码。

     var express = require('express');
     var app = express();
     var request=require("request");
    const bodyParser = require('body-parser');
    app.use(bodyParser.json());
     app.use(function(req, res, next) {
            res.header("Access-Control-Allow-Origin", "*");
            res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With,    Content-Type, Accept,clientSecret");
            res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,PATCH,DELETE,OPTIONS');

            next();
      });

      app.post("/push/v1/apps/:appID/devices",function(req,response){
                var appID=req.params.appID;
            var options={
                url:"https://pushapp.sampleapp.net/push/v1/apps/"+appID+"/devices",
                headers:{
                    'Content-Type':req.headers["content-type"],
                    'clientSecret':req.headers["clientsecret"]
                },
                body: JSON.stringify(req.body)
            }
               request.post(options,function(err,res,body){
                if(res.statusCode==201){  
                    response.sendStatus(201).json(JSON.parse(body));
                }
                else{
                    response.sendStatus(res.statusCode);
                }

            });

            });

请您帮助理解原因。我可以以某种方式猜测回调发生了两次。但不确定如何。

最佳答案

问题在于 res.sendStatus 设置给定的响应 HTTP 状态代码并将其字符串表示形式作为响应正文发送(请参阅 documentation )。 res.json 将设置内容类型响应 header ,但在某个时间响应将已经发送到客户端。

因此,您可以简单地使用 res.status,而不是使用 res.sendStatus:

response.status(201).json(JSON.parse(body));

关于node.js - 错误 [ERR_HTTP_HEADERS_SENT] : Cannot set headers after they are sent to the client - Express + Request,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55673691/

相关文章:

javascript - Node.js HTTP 获取 URL 长度限制

javascript - 我应该如何在 Node 中执行此操作?一条快路和一条慢路

javascript - 仅在一天中的特定时间按设定的时间间隔运行函数

javascript - 无法在 Express + Passport 应用程序/身份验证测试中发布

node.js - NodeJs错误: Can't set headers after they are sent

node.js - Express 3.0 bodyParser 无法正常工作

Node.js(带有 express 和 bodyParser): unable to obtain form-data from post request

javascript - 将数组发送到 promise 链

javascript - 快速路由分离

css - 使用 express 中间件应用 CSS 样式