我使用node.js服务器向我的前端发送响应。当我在MyNodeServer.js代码中添加setHeaders时,我收到'无法在发送后设置标头'错误。我的代码粘贴在下面。
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);
答案 0 :(得分:4)
不止一次发送回应。 (由于声誉低,无法发表评论。)
状态代码被写入两次。
更改
response.writeHead(405, {'content-type':'text/html'});
到
response.setHeader('content-type', 'text/html');