2015-09-08 26 views
0

我有一個節點快速應用和已經寫了一點中間件做到以下幾點:不能設置頭它們是從快遞中間件發送錯誤後

  • 檢查所有傳入的請求,如果它從一個機器人
  • 通過
  • 允許對原材料資源的請求如果請求是從一個機器人,服務器HTML快照

我從下面的代碼得到以下錯誤:

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(); 

}); 

回答

0

(如果第一個語句失敗並轉到catch塊,你在這裏做)

try { res.sendFile(snapshotDir + path); } //serve html snapshot 
catch (err) { res.send(404); } //no snapshot available, serve 404 error 

你應該試着去了解你不能爲一個請求寫兩次res.send爲什麼錯誤發生,然後在發送文件之前自己檢查一下。

大概文件不存在(可以使用fs.statSync

+0

感謝檢查,你的回答幫我一個解決方案,但有一件事你錯過了該'下一個()'也導致問題最後,我把它移到了接近頂端的if語句中。 – Coop

相關問題