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

ReactJS使用Axios请求报错Cannot read properties of undefined (reading 'protocol')求助

问题原因及修复方案

报错uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'protocol')是你的代码存在多处配置和语法错误导致的,具体问题及修复方法如下:

  • 首先是最直接的报错原因:请求地址未正确赋值。你代码中url: url这里的url变量没有赋值为curl对应的接口地址https://myurlpath.com/test/call,Axios解析非法的undefined地址时,无法读取协议字段就会抛出该错误。如果url变量已经单独定义,要检查当前作用域是否可以正常访问到该变量,避免变量值为undefined。
  • 请求头配置字段写错:Axios的请求头配置字段是复数形式headers,你写的单数header会导致自定义的Content-Type、Authorization请求头不生效,接口会返回400/401类错误。
  • 响应处理方法误用:res.json()是原生fetch API的用法,Axios会自动将响应体解析为JSON格式,存放在res.data字段中,直接调用res.json()会抛出方法不存在的错误。
  • 异常捕获逻辑失效:你使用了async语法,但没有对axios请求加await关键字,异步抛出的错误无法被外层的try/catch捕获,才会出现uncaught (in promise)的未捕获Promise异常提示。

修复后可正常运行的代码

async function call () {
  try {
    const res = await axios({
      method: 'post',
      // 直接写死接口地址,也可以提前将url变量赋值为这个地址
      url: 'https://myurlpath.com/test/call',
      headers: {
        "Content-Type": 'application/json',
        "Authorization": `Bearer ${USER_KEY}`
      },
      data: {
        // 确保script变量的值和curl中prompt的格式对齐,特殊字符转义正确
        prompt: script,
        temperature: 0,
        max_dist: 60,
        stat_request: 1.0,
        divider: ["\"\"\"\""]
      }
    })
    // 直接读取解析好的响应数据
    console.log(res.data)
  } catch (error) {
    console.error('请求出错:', error)
    return {statusCode: 500, body: error.toString()}
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 23:45:03