有条件地在get请求中使用中间件
use middleware in get request conditionally
我正在使用快速路线。这是我的要求
import { Router, Request, Response, NextFunction } from "express";
import { celebrate, Joi, Segments } from "celebrate";
const route = Router();
export default (app: Router) => {
route.get("/:id",
celebrate({
[Segments.PARAMS]: Joi.object({
id: Joi.string().required().label("Store Id")
})
}),
basicAuth, //a middleware
asyncHandler(async (req: Request, res: Response, next: NextFunction) => {
// some operations.
return res.status(202).json(storeDetails);
})
);
}
这里我如何有条件地使用 basicAuth
中间件,以便在 id=="me" 时使用 basicAuth
,否则使用另一个中间件 isAuth
。
如果满足条件,您可以手动调用中间件:
route.get("/:id",
celebrate({
[Segments.PARAMS]: Joi.object({
id: Joi.string().required().label("Store Id")
})
}),
asyncHandler(async (req: Request, res: Response, next: NextFunction) => {
if (req.params.id === "me") {
// call basicAuth middleware manually
basicAuth(req, res, err => {
if (err) {
// send error response here
next(err);
} else {
// continue processing here now that basicAuth has been verified
}
});
} else {
// not "me"
// some operations.
return res.status(202).json(storeDetails);
}
})
);
}
我正在使用快速路线。这是我的要求
import { Router, Request, Response, NextFunction } from "express";
import { celebrate, Joi, Segments } from "celebrate";
const route = Router();
export default (app: Router) => {
route.get("/:id",
celebrate({
[Segments.PARAMS]: Joi.object({
id: Joi.string().required().label("Store Id")
})
}),
basicAuth, //a middleware
asyncHandler(async (req: Request, res: Response, next: NextFunction) => {
// some operations.
return res.status(202).json(storeDetails);
})
);
}
这里我如何有条件地使用 basicAuth
中间件,以便在 id=="me" 时使用 basicAuth
,否则使用另一个中间件 isAuth
。
如果满足条件,您可以手动调用中间件:
route.get("/:id",
celebrate({
[Segments.PARAMS]: Joi.object({
id: Joi.string().required().label("Store Id")
})
}),
asyncHandler(async (req: Request, res: Response, next: NextFunction) => {
if (req.params.id === "me") {
// call basicAuth middleware manually
basicAuth(req, res, err => {
if (err) {
// send error response here
next(err);
} else {
// continue processing here now that basicAuth has been verified
}
});
} else {
// not "me"
// some operations.
return res.status(202).json(storeDetails);
}
})
);
}