gpt4 book ai didi

javascript - 另一个 "can' t 在发送后设置 header ”

转载 作者:行者123 更新时间:2023-11-30 09:31:42 24 4
gpt4 key购买 nike

我使用 node.js 服务器向我的前端发送响应。当我在我的 MyNodeServer.js 代码中添加 setHeaders 时,出现“发送后无法设置 header ”错误。我的代码已粘贴在下面。

   web server listening to port 8080, started
_http_outgoing.js:367
throw new Error('Can\'t set headers after they are sent.');
^

Error: Can't set headers after they are sent.
at ServerResponse.setHeader (_http_outgoing.js:367:11)
at ServerResponse.writeHead (_http_server.js:183:21)
at ...\MyNodeServer.js:71:26
at FSReqWrap.readFileAfterClose [as oncomplete] (fs.js:416:3)

MyNodeServer.js

var myHttp = require("http");
var url = require("url");
var qString = require("querystring");
var fs = require('fs');

var myEvents = require('./customEvents');

var myAppWebServer = myHttp.createServer(function(request, response){

response.setHeader('Access-Control-Allow-Origin', 'http://localhost:8080');

response.setHeader('Access-Control-Allow-Methods',
'GET, POST, OPTIONS, PUT, PATCH, DELETE');

response.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
response.setHeader('Access-Control-Allow-Credentials', true);

if (request.method === "OPTIONS") {
return response.status(200).end();
}

var query =url.parse(request.url).query;
response.writeHead(405, {'content-type':'text/html'});
var yourVisit;
var pName = url.parse(request.url).pathname;
if(pName==='/register'){
response.end('{ "name":"xxx", "city":"yyy"}');
}else if (pName==='/login'){
fs.readFile("pages/login.html", function (error, pgResp) {
response.writeHead(200, { 'Content-Type': 'text/html' });
response.write(pgResp);
response.end();
});
}
});

myAppWebServer.listen(8080);

最佳答案

响应被发送了不止一次。 (由于信誉不佳,无法发表评论。)

状态码写了两次。

改变

response.writeHead(405, {'content-type':'text/html'});

response.setHeader('content-type', 'text/html');

关于javascript - 另一个 "can' t 在发送后设置 header ”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45832560/

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