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

React Hooks中使用Fetch API出现Unexpected end of input错误如何解决

问题根因
  • mode: 'no-cors' 配置的作用是允许发送跨域请求,但会将响应设置为*不透明(opaque)*类型,浏览器会禁止你读取响应的任何内容,包括状态码、响应体。
  • 你尝试调用.json()或.text()解析空的响应体,自然会抛出Unexpected end of input错误,这是浏览器同源策略的强制限制,和解析逻辑无关。
解决方案
  1. 优先配置服务端CORS(如果API属于你可管控的范围)

给API服务端添加CORS响应头,允许你的前端域名访问:
Access-Control-Allow-Origin: 你的前端域名
调试阶段也可以临时设置为*允许所有域名访问,配置完成后删除fetch参数里的mode: 'no-cors'即可正常请求。

  1. 使用代理转发请求(如果API无法修改CORS配置)

开发环境可以直接用构建工具的代理能力:比如Vite在vite.config.js里配置server.proxy,Webpack在devServer.proxy里配置,将本地路径转发到目标API地址。生产环境可以用Nginx反向代理配置同域路径转发,这样前端请求的是同域路径,不存在跨域问题,不需要加no-cors参数。

修正后的代码示例
const [isLoading, setIsLoading] = useState(false)
const [drivers, setDrivers] = useState([])
const [error, setError] = useState(null)

useEffect(() => {
  const fetchData = async () => {
    setIsLoading(true) // 请求开始前先设置加载状态
    try {
      // 移除mode: no-cors,走代理或者服务端已经配置CORS
      const response = await fetch('https://dummy-api.com/api/drivers')
      if (!response.ok) throw new Error('请求响应异常')
      const data = await response.json()
      setDrivers(data.drivers)
      console.log(data)
    } catch (error) {
      setError(error)
      console.log(error.message)
    } finally {
      setIsLoading(false) // 无论成功失败都关闭加载状态
    }
  }
  fetchData()
}, [])

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.11 15:03:04