[英]How to use middleware in all http request in nodejs express
I am creating a middleware in the nodejs application and I want to add header in the request in middleware and send it to the my endpoint index.js request. 我正在nodejs应用程序中创建一个中间件,我想在中间件的请求中添加标头,并将其发送到我的端点index.js请求。
middleware1.js middleware1.js
exports.mw1 = function(req, res, next) {
next();
};
middleware2.js middleware2.js
exports.mw2 = function(req, res, next) {
next();
};
app.js app.js
var mw1 = require("./middlewares/middleware1");
var mw2 = require("./middlewares/middleware2");
var combinedMiddleware = function compose(middleware) {
return function(req, res, next) {
connect
.apply(null, middleware.concat(next.bind(null, null)))
.call(null, req, res);
};
};
app.use(combinedMiddleware([auth, audit]));
app.use("/", index);
index.js index.js
var express = require("express");
var router = express.Router();
router.get("/", function(req, res) {
res.send("Welcome!!");
});
module.exports = router;
When I am trying to call it http://localhost:3000/ then it returns the 404 Not Found. 当我尝试将其命名为http:// localhost:3000 /时,它将返回404 Not Found。 Instead, it should redirect request to both middleware then to the index.js
相反,它应该将请求重定向到两个中间件,然后再重定向到index.js
GET / 404 8.700 ms - 139
Does anyone know whats wrong with it ? 有谁知道这是怎么回事?
Maybe I am missing something, but why you don't do: 也许我缺少了一些东西,但是为什么你不这样做:
var mw1 = require("./middlewares/middleware1");
var mw2 = require("./middlewares/middleware2");
app.use(mw1, mw2);
app.use("/", index);
And change your middleware to : 并将您的中间件更改为:
module.exports = function(req, res, next) {
next();
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.