NodeJS 是否可以禁用/删除一个中间件的特定路由在JavaScript?

l0oc07j2  于 11个月前  发布在  Node.js
关注(0)|答案(2)|浏览(97)

我想禁用一个特定的中间件,这是我之前在app.js中设置的,例如:

app.use(express.bodyParser());

字符串
然后我想删除特定路由的 bodyParser(),例如:

app.post("/posts/add", Post.addPost);


谢谢你

vsdwdz23

vsdwdz231#

你可以写一个函数来检测一个条件,像这样:

function maybe(fn) {
    return function(req, res, next) {
        if (req.path === '/posts/add' && req.method === 'POST') {
            next();
        } else {
            fn(req, res, next);
        }
    }
}

字符串
然后修改app.use语句:

app.use(maybe(express.bodyParser()));

bz4sfanl

bz4sfanl2#

在typescript中,你可以这样写一个except函数:

import { Request, Response, NextFunction, } from 'express';
type MiddlewareFn = (req: Request, res: Response, next: NextFunction) => void;

export const middlewareExcept =
    (fn: MiddlewareFn, except: string[]): MiddlewareFn =>
    (req, res, next) => {
        if (except.includes(req.path)) next();
        else fn(req, res, next);
    };

个字符

相关问题