nodejs如何从中间件中走出来

jmp7cifd  于 2021-09-13  发布在  Java
关注(0)|答案(3)|浏览(340)

我的api上有一些路由。并且有一个中间件。它创建承载令牌并检查它。但我希望我的一些路由不进入该中间件,这样我就可以在没有令牌的情况下访问。我怎样才能做到?我的中间件:

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);
    }
  }
});

我的路线:

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

rjjhvcjd1#

您这样做的方式是正确的,您可以通过创建一个包含您希望超出中间件范围的所有中间件的数组来提高代码的可读性

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

然后

// 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
})

或者你可以换快递 use 秩序

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

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

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

这里第一个路由器不会使用中间件,因为它还没有被调用。

gev0vcfq

gev0vcfq2#

可以创建管线 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)

对于身份验证,我建议创建一个单独的中间件,然后将其传递给我们的路由

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);
    }
  }
}

我想,有了这个,你可能会有一些想法:)

qxsslcnc

qxsslcnc3#

你可以用 Express.Router 以达到预期的效果。使用express router,您可以区分不同的路由,并为每个路由器提供不同的中间件。
按照以下步骤操作:
创建一个auth中间件 middlewares/private.authenticate.js ```
function auth(req, res, next) {
// do auth stuff...
next();
}

创建一个文件 `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;

创建一个文件 routes/public/index.js ```
import { Router } from "express";

const router = Router();

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

export default router;

您的express应用程序文件

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);

相关问题