简体   繁体   English

无法在 ExpressJS 中将中间件应用于路由器?

[英]Unable to Apply Middleware to Router in ExpressJS?

I have an app where I have public routes and authenticated routes.我有一个应用程序,其中有公共路线和经过身份验证的路线。 isAuthenticated were applied for example to a news controller. isAuthenticated被应用于例如新闻 controller。

globalRouter: function (app) {
  app.use((req, res, next) => {
    logger.log("Endpoint: ", req.originalUrl);
    next();
  });
  const userRouter = require("./user/controller");
  const globalRouter = require("./global/controller");
  const newsRouter = require("./news/controller");

  app.use("/user", userRouter);
  app.use("/global", globalRouter);
  app.use("/news", middleware.isAuthenticated(), newsRouter); // here
}

And here is the isAuthenticated code written in middleware.js file.这是在 middleware.js 文件中编写的isAuthenticated代码。

const security = require("../utils/security");
const service = require("../user/service");

exports.isAuthenticated = function (req, res, next) {
  let authorization = req.headers.authorization;
  let token = null;
  if (authorization.startsWith("Bearer ")) {
    token = authorization.substring(7, authorization.length);
    if (token !== null) {
      service.checkUserTokenMiddleware(token, security).then((response) => {
        console.log("checkUserTokenMiddleware", response);
        if (response) {
          next();
        }
      });
    }
  }
};

The problem is that I'm getting this error below when I npm start the app问题是当我npm 启动应用程序时出现以下错误

TypeError: Cannot read property 'headers' of undefined at Object.exports.isAuthenticated TypeError:无法读取 Object.exports.isAuthenticated 处未定义的属性“标题”

What am I missing here?我在这里想念什么?

why do I get such an error meanwhile in my other file using the same method like req.body.blabla or req.headers.blabla is fine?为什么我在其他文件中同时使用req.body.blablareq.headers.blabla之类的相同方法会出现这样的错误?

Any help will be much appreciated.任何帮助都感激不尽。

Regards.问候。

Simply remove the brackets after the function call:只需在 function 调用后删除括号:

app.use("/news", middleware.isAuthenticated, newsRouter);

You don't have to call the function in the callback to app.use , Express will itself pass in req,res,next to the auth function and call it.您不必在 app.use 的回调中调用app.use ,Express 本身会传入req,res,next auth function 旁边并调用它。

It depends on how you import, middleware.js .这取决于您如何导入middleware.js Since you are exporting, isAuthenticated as function.由于您正在导出,因此被验证为isAuthenticated This should be not called before passing to app.use .在传递给app.use之前不应调用它。

Other things to be noticed, you never call the next function on error or else.其他需要注意的事情,你永远不要在错误或其他情况下调用下一个 function。

Please have a look in the below example.请看下面的例子。

// middleware.js // 中间件.js

const security = require("../utils/security");
const service = require("../user/service");

exports.isAuthenticated = function (req, res, next) {
  let authorization = req.headers.authorization;
  let token = null;
  if (authorization.startsWith("Bearer ")) {
    token = authorization.substring(7, authorization.length);
    if (token !== null) {
      service
        .checkUserTokenMiddleware(token, security)
        .then((response) => {
          if (response) {
            next();
          }
        })
        .catch((error) => next(error));
    } else {
      next("UNAUTHORIZED");
    }
  } else {
    next("UNAUTHORIZED");
  }
};

// app.js // 应用程序.js

const middleware = require("./middleware")

app.use((req, res, next) => {
  logger.log("Endpoint: ", req.originalUrl);
  next();
});
const userRouter = require("./user/controller");
const globalRouter = require("./global/controller");
const newsRouter = require("./news/controller");

app.use("/user", userRouter);
app.use("/global", globalRouter);
app.use("/news", middleware.isAuthenticated, newsRouter); // here

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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