Axios请求未传数据致后端Yup验证报错:req.name必填问题
问题原因
后端的Yup验证Schema结构错误:你当前的Schema在验证req.req.name这个不存在的字段,但前端发送的参数实际上存放在Express请求对象的req.body属性中,而非req.req里。
解决方案
有两种修改方式可以解决这个问题:
方式一:调整Schema以验证req.body
修改后端的Schema,将嵌套的req键替换为body,这样就能正确匹配请求体中的数据:
import { Request, Response } from "express"; import * as yup from "yup"; import ElectionContract, { web3 } from "../../web3"; const schema = yup.object({ body: yup.object({ name: yup.string().min(3).required(), description: yup.string().min(10).required(), candidates: yup.array( yup.object({ name: yup.string().min(3), info: yup.string().min(10), }) ), }), }); export default async (req: Request, res: Response) => { try { await schema.validate(req); } catch (error: any) { return res.status(400).send(error.errors); } };
方式二:直接验证req.body(更简洁)
直接针对req.body编写Schema,验证时传入req.body而非整个req对象:
import { Request, Response } from "express"; import * as yup from "yup"; import ElectionContract, { web3 } from "../../web3"; // 直接定义请求体的验证规则 const schema = yup.object({ name: yup.string().min(3).required(), description: yup.string().min(10).required(), candidates: yup.array( yup.object({ name: yup.string().min(3), info: yup.string().min(10), }) ), }); export default async (req: Request, res: Response) => { try { // 验证req.body而非整个req对象 await schema.validate(req.body); } catch (error: any) { return res.status(400).send(error.errors); } };
额外检查
确认前端发送的candidates数组中的每个对象都包含name和info字段(符合后端Schema的要求),避免后续出现其他验证错误。
内容的提问来源于stack exchange,提问作者Khushi
相关产品推荐
相关产品推荐

