【发布时间】:2020-07-22 04:51:57
【问题描述】:
所以我正在使用 TypeScript 在 Express 中开发一个注册路由处理程序。我使用express-validators 来避免我必须在路由处理程序中写出的所有这些代码,但是在我快速浏览的文档中,我没有看到username 的示例,只有email 的示例。任何有更多经验的人都知道我是否可以仅对password 和passwordConfirmation 实施验证,对username 进行硬代码验证?
这是我目前所拥有的:
import express, { Request, Response } from "express";
import { body } from "express-validator";
const router = express.Router();
router.post(
"/auth/signup",
[
body("password")
.trim()
.isLength({ min: 4, max: 20 })
.withMessage("Must be between 4 and 20 characters"),
body("passwordConfirmation").custom((value, { req }) => {
if (value !== req.body.password) {
throw new Error("Passwords must match");
}
}),
],
(req: Request, res: Response) => {
const { username, password, passwordConfirmation } = req.body;
// const existingUser = await usersRepo.getOneBy({ username });
// if (existingUser) {
// return res.status(422).send({ username: "Username already in use" });
// }
// const user = await usersRepo.create({
// username,
// password,
// passwordConfirmation,
// });
// req.session.userId = user.id;
// res.status(200).send({ username: req.body.username });
}
);
export { router as signupRouter };
当然我知道我在回调前面缺少async 以使用注释掉的内容。
我注释掉的内容会在与express-validators 相同的环境中工作吗?
【问题讨论】:
标签: typescript express express-validator