JavaScript使用fetch发起GET请求获取API字符串响应返回空串求助
问题背景
- 编辑补充:此前参考的解决方案不生效
- 目标接口返回字符串类型的响应,正常返回效果如下图:

- 编写JavaScript fetch请求获取该接口内容时,控制台打印结果为空字符串,当前代码如下:
fetch("https://xxxxxxxxxxxxxxxxx", { "method": "GET", "headers": { "Content-Type": "application/json", "Access-Control-Allow-Origin" : "*", "Access-Control-Allow-Credentials" : true , "authority": "clientportal.webresults-nt.com", "sec-ch-ua": "\" Not A;Brand\";v=\"99\", \"Chromium\";v=\"96\", \"Google Chrome\";v=\"96\"", "accept": "q=0.8;application/json;q=0.9", "content-type": "application/json; charset=utf-8", "user-token": "", "sec-ch-ua-mobile": "?0", "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.45 Safari/537.36", "sec-ch-ua-platform": "\"Windows\"", "origin": "https://xxxxxxxxxxxxxxxxx", "sec-fetch-site": "cross-site", "sec-fetch-dest": "empty", "referer": "https://xxxxxxxxxxxxxxx/", "accept-language": "ar,en-US;q=0.9,en;q=0.8,fa;q=0.7,fr;q=0.6,ms;q=0.5,tr;q=0.4" } }) .then(response => response.text()) .then((response) => { console.log(response) }) .catch(err => console.log(err))
空返回的控制台效果如下图:
解决方案
你代码里的请求头配置存在多处错误,逐一修正即可解决空返回问题:
- 删除错误的跨域头字段
Access-Control-Allow-Origin和Access-Control-Allow-Credentials是服务端返回响应时需要设置的响应头,请求端主动添加这两个字段属于错误配置,会触发跨域校验规则,导致接口返回异常。 - 修正Accept请求头格式
你当前的Accept头q=0.8;application/json;q=0.9格式完全不符合规范,正确的写法是先声明可接受的资源类型,再紧跟权重配置,示例:application/json;q=0.9, text/plain;q=0.8。格式错误会导致服务端无法识别你能接受的返回类型,直接返回空内容。 - 删除多余的Content-Type字段
GET请求没有请求体,不需要设置Content-Type,你的代码里还重复设置了两次该字段,属于无效配置,会增加服务端解析异常的概率。 - 检查鉴权参数有效性
当前配置里user-token为空值,如果该接口需要登录后访问,空token会导致服务端直接拒绝返回业务数据,需要补充你账号对应的有效token值。
修正后的参考代码:
fetch("https://xxxxxxxxxxxxxxxxx", { method: "GET", headers: { "authority": "clientportal.webresults-nt.com", "sec-ch-ua": "\" Not A;Brand\";v=\"99\", \"Chromium\";v=\"96\", \"Google Chrome\";v=\"96\"", "accept": "application/json;q=0.9, text/plain;q=0.8, */*;q=0.7", "user-token": "这里替换为你的有效用户token", "sec-ch-ua-mobile": "?0", "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.45 Safari/537.36", "sec-ch-ua-platform": "\"Windows\"", "origin": "https://xxxxxxxxxxxxxxxxx", "sec-fetch-site": "cross-site", "sec-fetch-dest": "empty", "referer": "https://xxxxxxxxxxxxxxx/", "accept-language": "ar,en-US;q=0.9,en;q=0.8,fa;q=0.7,fr;q=0.6,ms;q=0.5,tr;q=0.4" } }) .then(response => { // 可以先打印响应状态码,确认接口是否正常响应 console.log('响应状态码:', response.status) return response.text() }) .then(response => { console.log('响应内容:', response) }) .catch(err => console.log('请求报错:', err))
内容的提问来源于stack exchange,提问作者Sermed mayi
相关产品推荐
相关产品推荐

