Vercel部署MERN应用遇JSON解析错误,本地正常求助
解决Vercel部署MERN应用后JSON解析错误:Unexpected token '<'
问题根源分析
错误提示Unexpected token '<', "<!doctype "... is not valid JSON说明前端请求的API路径返回了HTML内容(大概率是404页面),而非预期的JSON响应。结合你的场景,核心问题有两个:
- API请求路径配置错误(Vercel环境变量或路由路径不匹配)
- 后端响应未使用标准JSON格式,导致前端解析失败
分步解决方案
1. 排查并修正API请求路径
- 打开浏览器开发者工具「网络」面板,定位
/users/profile请求,查看实际请求URL和响应内容:- 如果响应是HTML(比如Vercel的404页面),说明
process.env.API_URL在Vercel上配置错误:- 若前后端同项目部署(使用Vercel Serverless Functions),API路径应为
/api/users/profile(对应项目api文件夹下的后端路由) - 若前后端分离部署,确保
API_URL指向正确的后端Vercel域名(而非本地localhost)
- 若前后端同项目部署(使用Vercel Serverless Functions),API路径应为
- 如果响应是HTML(比如Vercel的404页面),说明
- 验证Vercel环境变量:进入项目设置→环境变量,确认
API_URL的值与部署后的后端地址完全一致
2. 统一后端响应为JSON格式
你的后端代码中使用res.send(false)或直接返回false,会导致响应为text/plain格式而非application/json,前端res.json()解析时必然失败。修改如下:
路由代码修改
router.get("/profile", auth.verify, (req, res) => { const userData = auth.decode(req.headers.authorization); if (userData) { userController.getProfile({id: userData.id}) .then(result => { // 统一返回JSON格式,无数据时返回失败标识 res.json(result || { auth: "failed" }); }) .catch(err => { res.json({ auth: "failed", error: err.message }); }); } else { // 直接返回JSON格式的失败响应 res.json({ auth: "failed" }); } });
控制器代码修改
module.exports.getProfile = (reqBody) => { return User.findById(reqBody.id) .then(result => { if (!result) { // 返回标准JSON失败结构,而非false return { auth: "failed" }; } else { result.password = "************"; return result; } }) .catch(err => { // 捕获数据库错误,返回统一JSON结构 return { auth: "failed", error: err.message }; }); };
3. 前端添加错误捕获逻辑
在fetch链中加入错误处理,避免解析失败导致应用崩溃:
useEffect(() => { fetch(`${process.env.API_URL}/users/profile`, { headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${localStorage.getItem('token')}` } }) .then(res => { // 先校验响应状态,非200状态抛出错误 if (!res.ok) { throw new Error(`请求失败,状态码:${res.status}`); } return res.json(); }) .then(data => { console.log(data); if (data._id) { setUser({ id: data._id, isAdmin: data.isAdmin }); } else { setUser({ id: null, isAdmin: null }); } }) .catch(err => { console.error('请求或解析错误:', err); // 错误时重置用户状态 setUser({ id: null, isAdmin: null }); }); }, []);
验证步骤
- 重新部署前后端到Vercel
- 打开浏览器网络面板,确认
/users/profile请求返回Content-Type: application/json - 检查控制台,确认JSON解析正常,无语法错误
内容的提问来源于stack exchange,提问作者janie
相关产品推荐
相关产品推荐

