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
相关产品推荐
相关产品推荐

