繁体   English   中英

从Express中间件发送错误后无法设置标题

[英]Can't set headers after they are sent error from Express middleware

我有一个Node Express应用程序,并写了一些中间件来执行以下操作:

  • 检查所有传入请求是否来自机器人
  • 允许通过以下方式请求原始资源
  • 如果请求来自机器人,则向服务器提供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();

});

您不能为一个请求编写两次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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM