使用GET请求调用API时Fetch执行失败的问题求助
解决GET请求带请求体引发的fetch报错问题
错误提示已经说得很明确:TypeError: Failed to execute 'fetch' on 'Window': Request with GET/HEAD method cannot have body.——HTTP规范里明确GET、HEAD这类请求不能携带请求体,浏览器的fetch API会直接拦截这种不符合规范的请求,所以你的代码执行失败了。
下面是两种可行的解决办法:
方案1:通过URL查询参数传递userId
把userId放到URL的查询字符串里,这是GET请求传递参数的标准方式,修改后的代码如下:
var requestOptions = { method: 'GET', redirect: 'follow' }; fetch("https://mcqapi.onrender.com/api/dashboard?userId=1", requestOptions) .then(response => response.text()) .then(result => console.log(result)) .catch(error => console.log('error', error));
注意:需要确保后端接口能从URL查询参数中读取userId的值。
方案2:改用POST请求传递请求体
如果后端允许用POST方法处理这个请求,就把请求方法改成POST,保留请求体传递参数,代码修改如下:
var myHeaders = new Headers(); myHeaders.append("Content-Type", "application/json"); var raw = JSON.stringify({ "userId": 1 }); var requestOptions = { method: 'POST', headers: myHeaders, body: raw, redirect: 'follow' }; fetch("https://mcqapi.onrender.com/api/dashboard", requestOptions) .then(response => response.text()) .then(result => console.log(result)) .catch(error => console.log('error', error));
这种方式适合传递复杂参数,但前提是后端接口已经配置为接收POST请求并解析请求体中的数据。
内容的提问来源于stack exchange,提问作者Ahmed Ali
相关产品推荐
相关产品推荐

