我在尝试读取文件并将响应发送回浏览器时遇到错误。
[ 'Error: Can\'t set headers after they are sent.',
' at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:344:11)',
' at ServerResponse.setWriteHeadHeaders (/somepath/node_modules/on-headers/index.js:82:19)',
' at ServerResponse.writeHead (/somepath/node_modules/on-headers/index.js:41:36)',
' at /somepath/server/custom.js:71:13',
' at FSReqWrap.readFileAfterClose [as oncomplete] (fs.js:380:3)' ]
var fs = require('fs');
exports.customPageChatStatus = function(req, res) {
if(req.params._pagename === 'Test123')
{
fs.readFile("/somepath/Test123.txt", 'utf-8', function(err, data) {
if (err) console.log(err);
res.writeHead(200, {'Content-Type':'text/plain', 'Access-Control-Allow-Origin':'*' });
res.end(data);
});
}
if(req.params._pagename === 'SecondFile')
{
fs.readFile("/somepath/SecondFile.txt", 'utf-8', function(err, data) {
if (err) console.log(err);
res.writeHead(200, {'Content-Type':'text/plain', 'Access-Control-Allow-Origin':'*' });
res.end(data);
});
}
else {
fs.readFile("/somepath/InActive.txt", 'utf-8', function(err, data) {
res.writeHead(200, {'Content-Type':'text/plain', 'Access-Control-Allow-Origin':'*' });
res.end(data);
});
}
};

有趣的是,我只是在阅读第一个文件(Test123.txt)时才看到上述错误,在阅读" SecondFile.txt"时没有问题。
感谢您解决此问题的任何帮助!
答案 0 :(得分:0)
此处如果您在声明中使用else,则会解决您的问题
var fs = require('fs');
exports.customPageChatStatus = function(req, res) {
if(req.params._pagename === 'Test123')
{
fs.readFile("/somepath/Test123.txt", 'utf-8', function(err, data) {
if (err) console.log(err);
res.writeHead(200, {'Content-Type':'text/plain', 'Access-Control-Allow-Origin':'*' });
res.end(data);
});
}
else if(req.params._pagename === 'SecondFile')
{
fs.readFile("/somepath/SecondFile.txt", 'utf-8', function(err, data) {
if (err) console.log(err);
res.writeHead(200, {'Content-Type':'text/plain', 'Access-Control-Allow-Origin':'*' });
res.end(data);
});
}
else {
fs.readFile("/somepath/InActive.txt", 'utf-8', function(err, data) {
res.writeHead(200, {'Content-Type':'text/plain', 'Access-Control-Allow-Origin':'*' });
res.end(data);
});
}
};
答案 1 :(得分:0)
令人惊讶的是if..else if ..实际上是一个问题。我确定这两种情况永远不会成真。
我想到了一种更简洁的方法。
更简单的代码:
var fs = require('fs');
exports.customPageChatStatus = function(req, res) {
let pagename = req.params.pagename;
if (pagename !== 'Test123' || pagename !== 'Secondfile') pagename = 'InActive';
fs.readFile(`/somepath/${pagename}.txt`, 'utf-8', function(err, data) {
if (err) return console.log(err);
res.writeHead(200, {'Content-Type':'text/plain', 'Access-Control-Allow-Origin':'*' });
return res.end(data);
});
};