You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

调用fetch()获取返回字符串值时报JSON解析错误如何解决

问题解决方案

根因定位

你触发的报错是因为后端接口返回的是纯文本字符串(比如SUCCESFULLY REGISTERED NEW USER、EMAIL EXISTS!),但前端fetch回调中强制使用.json()方法解析响应,该方法仅支持解析合法JSON格式内容,解析普通字符串就会抛出Unexpected token S in JSON at position 0类的语法错误。

可选解决方案

方案1(推荐,符合接口开发规范):修改后端返回格式为标准JSON

将后端所有返回内容封装为JSON对象,避免纯文本返回:

  1. 修改Usercontroller.js的返回逻辑:
module.exports.register = (reqBody)=>{
  //check if email already exists before registering new user
  return User.find({email: reqBody.email}).then((result, error) =>{
    if(result.length != 0){
      // 封装为JSON对象返回
      return {code: 400, msg: "EMAIL EXISTS!"};
    }else{
      let newUser = new User({
        firstName: reqBody.firstName,
        lastName: reqBody.lastName,
        email:reqBody.email,
        password: bcrypt.hashSync(reqBody.password, 10),
        mobileNo: reqBody.mobileNo
      })
      return newUser.save().then((result, error)=>{
        if (error){
          return {code: 500, msg: error.message || "注册失败"};
        }else{
          return {code: 200, msg: "SUCCESFULLY REGISTERED NEW USER"};
        }
      })
    }
  })
}
  1. 优化路由返回方法,使用res.json()替代res.send(),更符合JSON接口规范:
router.post('/register', (req, res)=>{
  userController.register(req.body).then(result => res.json(result))
})

修改完成后前端原有解析逻辑不需要改动,就能正常拿到返回数据,还可以通过code字段判断请求状态做后续业务处理。

方案2(无需改后端,临时适配):修改前端响应解析方式

如果暂时不想调整后端代码,直接将前端的响应解析方法从.json()改为.text(),适配纯文本返回:

fetch(`${rootUrl}api/users/register`,{
  method:"POST",
  headers:{
    "Content-Type": "application/json"
  },
  body:JSON.stringify({
    firstName: firstName,
    lastName: lastName,
    mobileNo: mobileNo,
    email: email,
    password: password
  })
})
// 把json()改为text()解析纯文本
.then(result=>result.text())
.then(result =>{
  console.log(result);
})
// 补充异常捕获,方便后续排查问题
.catch(err => console.error('请求异常:', err))

内容的提问来源于stack exchange,提问作者quielfala

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 12:30:00