简体   繁体   English

NodeJS 如何使我的路由脱离中间件

[英]NodeJS How can i make my route out of middleware

I have some routes on my API.我的 API 上有一些路由。 And have a middleware.并有一个中间件。 Its creating bearer token and checking it.它创建不记名令牌并检查它。 But i want some of my routes dont enter to that middleware so i can access without token.但是我希望我的一些路由不要进入该中间件,这样我就可以在没有令牌的情况下访问。 How can i make it ?我怎样才能做到? My middleware :我的中间件:

  app.use(async (req, res, next) => {
  if (
    req.path === "/api/v1/collection/byhome" ||  // I dont want that part.
    req.path === "/api/v1/user/login" // Its working but its not looks like best solution.
  ) {
    next();
  } else {
    const bearerHeader = req.header("authorization");
    if (typeof bearerHeader !== "undefined") {
      const bearer = bearerHeader.split(" ");
      const bearerToken = bearer[1];
      req.token = bearerToken;

      jwt.verify(req.token, process.env.SECRETKEY, async (err, authData) => {
        if (err) {
          res.sendStatus(401);
        } else {
          next();
        }
      });
    } else {
      res.statusCode = 400;
      const Response = {
        message: "Invalid Token",
        StatusCode: res.statusCode,
      };

      res.json(Response);
    }
  }
});

My Route :我的路线:

app.get(
  `/api/${version}/article/bycollection/:id`,
  ArticleRoute.getbycollection
);

your way of doing it is correct you can make your code more readable by making an array of all the middleware you want to be out of scope of your middleware您这样做的方式是正确的,您可以通过制作一个包含您想要超出中间件范围的所有中间件的数组来使您的代码更具可读性

const whiteListEndpoints = ["/api/v1/this", "/api/v1/this1", "/api/v1/this2"]

then然后

// your middleware
app.use((req, res,next) => {
    //if the path was in the whitelist just call next function
    if(whiteListEndpoints.includes(req.url)) return next()

    // let the middlware do it's job
})

or you can change your express use order或者您可以更改您的快递use顺序

const firstRoute = app.use("/no_middleware", router);

app.use((req, res, next) => {}) // your middleware

const secondRoute = app.use("/with_middleware", router);

here the first router won't use the middleware since it has not yet been called.这里第一个路由器不会使用中间件,因为它还没有被调用。

You can create a route express.Router() and set this to a path , this router have all auth, then create a second express.Router() and this without auth.您可以创建一个路由express.Router()并将其设置为path ,该路由器具有所有身份验证,然后创建第二个express.Router()并且没有身份验证。

var router = express.Router();
// your code for API auth...
router.get('/api/v1/collection/byhome',myMiddleware, (req, res, next) => {
  res.send('Hey There');
})
app.use('/api', router);
var routerGuest = express.Router();
//
routerGuest.get('/', (req, res, next) => {
  res.send('Hey There');
})
app.use('/guest', routerGuest)

for authentication, I recomend to make a separate middleware and then pass it to our route对于身份验证,我建议制作一个单独的中间件,然后将其传递给我们的路由

function myMiddleware(req, res, next){
const bearerHeader = req.header("authorization");
if (typeof bearerHeader !== "undefined") {
      const bearer = bearerHeader.split(" ");
      const bearerToken = bearer[1];
      req.token = bearerToken;

      jwt.verify(req.token, process.env.SECRETKEY, async (err, authData) => {
        if (err) {
          res.sendStatus(401);
        } else {
          next();
        }
      });
    } else {
      res.statusCode = 400;
      const Response = {
        message: "Invalid Token",
        StatusCode: res.statusCode,
      };

      res.json(Response);
    }
  }
}

I think with this you may have some idea to do it :)我想有了这个你可能会有一些想法:)

You can use Express.Router to achieve the desired result.您可以使用Express.Router来实现所需的结果。 With express router you can differentiate between routes and have different middlewares for each router.使用快速路由器,您可以区分路由并为每个路由器使用不同的中间件。

Follow the steps given below:请按照以下步骤操作:

  1. Create a auth middleware middlewares/private.authenticate.js创建一个 auth 中间件middlewares/private.authenticate.js
function auth(req, res, next) {
    // do auth stuff...
    next();
}
  1. Create a file routes/private/index.js创建文件routes/private/index.js
// private route handler
import { Router } from "express";
import auth from "./middlewares/private.authenticate.js";

const router = Router();

router.use(auth); // use auth middleware

router.route("/")
    .get()
    .put()

export default router;
  1. Create a file routes/public/index.js创建一个文件routes/public/index.js
import { Router } from "express";

const router = Router();

router.route("/")
    .get()
    .put()

export default router;
  1. Your express app file您的快递应用文件
import express from "express";
const app = express();

import PublicRoutes from "./routes/public";
import PrivateRoutes from "./routes/private";

// public routes path
app.use("/api/public", PublicRoutes);
// private routes path
app.use("/api/private", PrivateRoutes);

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

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