【问题标题】:exec a script on each request node.js在每个请求 node.js 上执行一个脚本
【发布时间】:2012-11-06 20:05:52
【问题描述】:

我确定每次使用 res 和 req var 执行请求(app.get 或 app.post)时,我都可以执行脚本或函数,但我找不到方法

你能帮帮我吗

谢谢

编辑:

我试试

var express = require('express')
, http = require('http')
, path = require('path');

var app = express();

app.use(function(err, req, res, next){
  console.log('aa');
  next();
});

在我的 app.js 中,但我的控制台中从来没有 aa

我的 app.get 在控制器中:

files = fs.readdirSync(__dirname + '/controllers');
files.forEach(function(file){
    var name = file.replace('.js', '');
    require('./controllers/' + name)(app, models);
});

如果我删除此代码 app.add 有效,但我无法使用 app.get

【问题讨论】:

  • 尝试从您的中间件函数中删除参数err

标签: node.js request express


【解决方案1】:

需要使用通用中间件:

app.use(function (req, res, next) {
  //do stuff
  next();
});

【讨论】:

  • 我编辑了我的帖子,我认为 app.use 必须设置在某个特定的地方
  • 因为您的中间件有 4 个参数,这意味着它是错误中间件。
猜你喜欢
  • 1970-01-01
  • 2014-05-18
  • 2018-10-16
  • 1970-01-01
  • 2014-03-07
  • 2020-11-05
  • 1970-01-01
  • 2020-12-12
  • 2013-07-17
相关资源
最近更新 更多