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

Node.js接口Postman正常,前端fetch调用res.json()报错求助

问题分析:fetch调用接口无法解析JSON的原因

问题场景

服务器端Node.js接口代码运行正常,用Postman调用能成功获取对象数组:

async getAll(req, res, next) {
  try {
    const result = await this.service.getAll(req.query);
    return res.json(result);
  } catch (e) {
    next(e);
  }
}

但前端用fetch调用时,服务器能收到请求并返回响应,却在执行res.json()时抛出错误:

Uncaught (in promise) SyntaxError: Unexpected end of input (at script.js:71:17)
at script.js:71:17

前端调用代码如下:

function Get() {
  fetch(`${basicUrl}`, { mode: 'no-cors' })
  .then((res) => {
    res.json();
  } )
  .then((data) => {
    printList(data);
  })
  .catch(err => { console.log("error" + err) });
}

问题原因

问题出在mode: 'no-cors'这个配置上:

  • 当fetch设置no-cors模式时,浏览器会强制限制前端对响应内容的访问权限,返回的是不透明响应(opaque response)
  • 这种响应的响应体完全无法被读取,哪怕服务器确实返回了JSON数据,前端也拿不到任何内容
  • 所以调用res.json()时,因为没有可解析的内容,就会抛出"Unexpected end of input"的语法错误

解决方法

  1. 移除mode: 'no-cors'配置:浏览器默认会发起带CORS检查的请求,不需要手动设置这个模式
  2. 服务器端配置CORS:在Node.js服务中添加CORS支持,比如使用cors中间件:
    const cors = require('cors');
    app.use(cors());
    
    配置后就能允许前端跨域请求,正常读取响应体并解析JSON了

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 09:52:07