首页 > 解决方案 > JS FetchAPI Get Request 添加原始正文数据

问题描述

我在 Postman 中有一个 GET 请求设置,原始正文数据如下,它可以工作。我可以从服务器获取数据 在此处输入图像描述

但是我的 Js fetch api 我不确定如何向它添加请求正文数据。这是我的 GET 请求配置

var requestOptions = {
  method: 'GET',
  headers: myHeaders,
  body: raw,
  redirect: 'follow'
};

fetch("https://example.net:/app/v1/cmp/displacer/url", requestOptions)
  .then(response => response.text())
  .then(result => console.log(result))
  .catch(error => console.log('error', error));

但它返回错误

error TypeError: Failed to execute 'fetch' on 'WorkerGlobalScope': Request with GET/HEAD method cannot have body.

服务器只接受对该 URL 的 GET 请求。我试图用谷歌搜索但没有运气。感谢您的时间。

标签: fetchpostmanfetch-api

解决方案


fetch 不支持在 GET 请求中发送 BODY(又名有效负载),因为它的行为在 HTTP 中未定义,并且许多其他系统不支持它或以意想不到的方式处理它。如果您需要发送一个 BODY,您可能应该使用与 GET 不同的方法;如果您需要在 GET 请求中发送参数,您可以尝试发送查询字符串


推荐阅读