我有一个Node Express应用程序,并编写了一些中间件来执行以下操作:
我从以下代码中收到以下错误:
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();
});
我不确定为什么会这样,有人可以帮忙吗?
{{1}}
答案 0 :(得分:0)
你不能为一个请求写两次res.send
(如果第一个语句失败并进入catch块,你在这里做的话)
try { res.sendFile(snapshotDir + path); } //serve html snapshot
catch (err) { res.send(404); } //no snapshot available, serve 404 error
您应该尝试理解错误发生的原因,然后在发送文件之前自行检查。
可能该文件不存在(您可以使用fs.statSync