首页 > 解决方案 > JS 将 XMLHttpRequest 转换为 Fetch 函数 (GET):无法在“窗口”上执行“获取”:使用 GET/HEAD 方法的请求不能有正文

问题描述

如何将旧的基于 XMLHttpRequest 的代码转换为 FETCH 函数?旧代码:

var data = JSON.stringify({
  "username": "user",
  "token": "12345"
});
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.open("GET", "http://localhost:5000/v1/data/users/");
xhr.setRequestHeader("Content-Type", "application/json");
xhr.send(data);

我无法通过 GET 请求发送数据字段

我试过了:

fetch (url, {method: 'GET',
             mode:"cors",
             body: JSON.stringify({
               username,
               token
             }),
             headers: {
               'Content-Type': 'application/json'
            }
       })

但我发现了 Fetch Error: TypeError: Failed to execute 'fetch' on 'Window': Request with GET/HEAD method cannot have body。

标签: getxmlhttprequestfetch

解决方案


推荐阅读