[英]Can't set headers after they are sent error from Express middleware
I have a Node Express app and have written a bit of middleware to do the following: 我有一个Node Express应用程序,并写了一些中间件来执行以下操作:
I'm getting the following error from the code below: 我从下面的代码中收到以下错误:
Error: Can't set headers after they are sent.
I'm not sure why this is happening, can anyone help? 我不确定为什么会这样,有人可以帮忙吗?
var snapshotDir = require("path").resolve(__dirname + "/../snapshots");
var bots = [
/facebookexternalhit/,
/googlebot/
];
var resources = [
/\/framework\//,
/\/partials\//,
/\/views\//
];
app.use(function(req, res, next){
//test user-agent against bots array
var isBot = function(agent){
return bots.some(function(bot){
return bot.test(new RegExp(agent));
});
}
//test path for raw resources
var isResource = function(path){
return resources.some(function(resource){
return resource.test(new RegExp(path));
});
}
//check request type
if (isResource(req.url)) return next(); //request is for raw resource
if (!isBot(req.get("user-agent")) && !/\?_escaped_fragment_=/.test(req.url)) return next(); //user-agent is not bot
//get url path without escaped fragment
var path = req.url.replace("?_escaped_fragment_=", "");
//format path into filename
if (path.charAt(0) !== "/") path = "/" + path; //prepend fragment with '/'
if (path === "/") path = "/index.html"; //home requested: serve index.html
if (path.indexOf(".html") == -1) path += ".html"; //append fragment with '.html'
//serve snapshot file
try { res.sendFile(snapshotDir + path); } //serve html snapshot
catch (err) { res.send(404); } //no snapshot available, serve 404 error
//next request
return next();
});
You can't write twice res.send
for one request (which you are doing here if the first statement fails and goes to the catch block) 您不能为一个请求编写两次
res.send
(如果第一条语句失败并转到catch块,则在此处执行此操作)
try { res.sendFile(snapshotDir + path); } //serve html snapshot
catch (err) { res.send(404); } //no snapshot available, serve 404 error
You should try to understand why the error occurs, then do a check yourself before sending the file. 您应该尝试了解为什么会发生错误,然后在发送文件之前先进行检查。
Probably the file doesn't exist (you can check that by using fs.statSync
该文件可能不存在(您可以使用
fs.statSync
检查
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.