我正在使用next-connect,并且只想将yup验证中间件应用于特定的路由(post)。包含路由的文件还包含其他路由(例如get、put)。有没有什么办法我可以只在我的post路由上应用yup验证中间件?或者这个文件只能包含我的post路由,而我的其他api路由,如get和put,将需要保存在另一个文件中?
下面是代码。感谢您的建议,谢谢
import nextConnect from "next-connect";
import bcrypt from "bcryptjs";
import middleware from "../../middlewares/middleware";
import yupValidator from "../../middlewares/yupValidator";
import { extractUser } from "../../lib/api-helpers";
const handler = nextConnect();
//! For Global Middlewares
handler.use(middleware);
handler
.post(async (req, res) => {
//! Apply yupValidator for this route only
const { name, password } = req.body;
console.log(name, body);
})
.get(async (req, res) => {
//! Do not apply yupValidator for this route
console.log(req);
});发布于 2020-11-14 13:14:56
import nc from "next-connect";
import bcrypt from "bcryptjs";
import * as yup from "yup";
import middleware from "../../middlewares/middleware";
import yupValidator from "../../middlewares/yupValidator";
import { extractUser } from "../../lib/api-helpers";
const userSchema = yup.object().shape({
name: yup.string().trim().required().min(3),
password: yup.string().required().min(5, "must be more than 5 words la"),
});
const handler = nc();
//! For Global Middlewares
const base = nc().use(middleware);
//! Route Specific Middlewares
const validation = nc().post("/api/users", yupValidator(userSchema));
handler
.use(base)
.use(validation)
.post(async (req, res) => {
//! Apply yupValidator for this route only
const { name, password } = req.body;
console.log(name, password);
res.status(201).send("Done");
})
.get(async (req, res) => {
//! yupValidator not applied to this get route
console.log(req);
})
.put(async (req, res) => {
//! yupValidator not applied to this put route
const { name, password } = req.body;
console.log(name, password);
res.status(201).send("Done");
});
export default handler;https://stackoverflow.com/questions/64830314
复制相似问题