Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/433.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ajax/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 事件排序ExpressJS/Node_Javascript_Node.js_Express - Fatal编程技术网

Javascript 事件排序ExpressJS/Node

Javascript 事件排序ExpressJS/Node,javascript,node.js,express,Javascript,Node.js,Express,我正在尝试使用事件在简单的ExpressJS web服务器中设置缓存控制头。代码如下所示: app.get('*', function (req, res, next) { helper.setCacheHeader.call(res, SIX_MONTHS); // If something goes wrong (and we know about it) remove the cache value res.on('nocache', function () { hel

我正在尝试使用事件在简单的ExpressJS web服务器中设置缓存控制头。代码如下所示:

app.get('*', function (req, res, next) {
  helper.setCacheHeader.call(res, SIX_MONTHS);
  // If something goes wrong (and we know about it) remove the cache value
  res.on('nocache', function () {
    helper.setCacheHeader.call(res, 0);
  });

  next();
});
这是路由器的第一条路由,因此每个非静态文件都将通过该路由。代码中有些地方可能出错,我只发送了一个空的200,并在
res
上发出“nocache”事件

if (err) {
  res.emit('nocache');
  return res.send(200, foo_bar)
}
当我触发错误事件时,这似乎起作用,我的缓存头按预期设置为0。然而,我盯着它看的时间越长,我对它的把握就越小


是否在响应结束之前解析了所有事件处理程序(
res.send
)?或者这真的是一种竞争条件,而我一直很幸运,所以它看起来很有效?

您的解决方案会有效,因为事件是以同步方式发出和接收的。通过使用
res.emit('nocache')
触发事件,
EventEmitter
调用当前线程中任何已注册的侦听器(因为node.js是单线程的)

EventEmitter
不使用
process.nextTick()
调用处理程序,因此为nocache事件注册的所有处理程序总是在
res.send()之前调用。您可以在中检查
EventEmitter
的实现