[英]Error: Cannot set headers after they are sent back to the client in express middleware
[英]Can't set headers after they are sent error from Express middleware
我有一個Node Express應用程序,並寫了一些中間件來執行以下操作:
我從下面的代碼中收到以下錯誤:
Error: Can't set headers after they are sent.
我不確定為什么會這樣,有人可以幫忙嗎?
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();
});
您不能為一個請求編寫兩次res.send
(如果第一條語句失敗並轉到catch塊,則在此處執行此操作)
try { res.sendFile(snapshotDir + path); } //serve html snapshot
catch (err) { res.send(404); } //no snapshot available, serve 404 error
您應該嘗試了解為什么會發生錯誤,然后在發送文件之前先進行檢查。
該文件可能不存在(您可以使用fs.statSync
檢查
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.