MERN注册时调用response.json()报JSON解析错误,数据存库但无提示不跳转
核心问题定位
- 你遇到的JSON解析报错,本质是前后端响应格式不匹配:前端代码在拿到后端响应后,直接调用
response.json()将返回体强制解析为JSON格式,但你后端所有路由的响应都是通过res.send()返回的无外层双引号的纯文本字符串(比如User registered Successfully),既没有合法的JSON结构,也不是符合规范的JSON字符串格式,解析时会在第一个字符的位置直接触发格式错误,完全对应报错提示里"unexpected character at line 1 column 1"的异常位置。 - 你观察到的运行现象完全和问题匹配:第44行的日志在fetch请求拿到response对象后就会执行,紧接着执行
response.json()时直接抛出未捕获的Promise异常,导致后续所有的日志输出、弹窗提示、路由跳转逻辑全部被阻断,哪怕用户数据已经成功写入数据库,前端流程也完全无法继续执行。
分步修复方案
第一步:统一后端响应为合法JSON格式
将所有使用res.send()返回纯文本的分支,全部替换为res.json()返回结构化JSON对象。res.json()会自动为响应设置正确的Content-Type: application/json头,和前端的解析逻辑完全匹配:
- 字段校验分支:
if(!name || !email || !phone || !work || !password || !cpassword){ return res.status(422).json({ error: "Please Fill All The Fields" }); } - 重复邮箱校验分支:
if(userExist){ return res.status(422).json({ error: "Email already exists" }); } - 密码一致性校验分支:
else if(password !== cpassword){ return res.status(422).json({ error: "Passwords are not matching" }); } - 注册成功分支:
user.save() .then(()=>{ res.status(201).json({ message: "User registered Successfully" }) }) .catch((err)=>{ res.status(500).json({ error: err.message }); }) - 补上之前缺失的外层查询错误响应(原来该分支只在控制台打印错误,没有给前端返回任何内容,会导致前端请求挂起超时):
}).catch((err)=>{ console.log(err); res.status(500).json({ error: "Server internal error, please retry later" }); })
第二步:调整前端判断逻辑适配返回结构
原来的if(data)判断逻辑无法适配结构化的JSON返回,同时优先使用HTTP状态码判断请求结果,比单纯校验返回体对象更可靠:
const postData = async(event) =>{ event.preventDefault(); const { name, email, phone, work, password, cpassword} = user; const response = await fetch('/register' , { method: 'POST', headers : { "Content-Type" : "application/json" }, body: JSON.stringify({ name: name, email : email, phone : phone, work : work, password: password, cpassword : cpassword }) }); console.log('1'); //line 44!!!! const data = await response.json(); console.log('1'); //line 48 // 用response.ok判断是否为2xx状态的成功请求 if(response.ok){ console.log('1'); //line 51 window.alert("registration successful"); console.log("registration successful"); history.push('/login'); }else{ console.log('1'); //line 58 window.alert(data.error || "Invalid registration"); console.log("Invalid registration", data.error); } console.log('1'); //line 63 }
补充检查项
- 确认Express应用在所有路由注册前,已经配置了JSON请求体解析中间件:
app.use(express.json()),没有这个中间件的话,req.body会是undefined,所有字段校验都会触发失败响应。 - 不要混用纯文本和JSON返回格式给前端的fetch请求,否则很容易触发同类解析错误。
内容的提问来源于stack exchange,提问作者Bhavesh Damor
相关产品推荐
相关产品推荐

