gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 01:32:26 24 4
gpt4 key购买 nike

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

下面是我使用 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/

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