如何向 javascript 的 fetch() 函数发送额外的数据

How do I sent additional data to javascript's fetch() function

我想使用 fetch() 查询支持我的搜索页面的 API 端点。它 returns JSON 格式的搜索结果列表。

我还想将用户当前提交的查询传递给API。旧的实现使用 jquery 和 getJSON。查看 getJSON 的文档,它说我可以传入一个 data 变量:

data
Type: PlainObject or String
A plain object or string that is sent to the server with the request.

Looking at the docs 对于获取,我不确定如何将数据作为请求的一部分传递。所以我的问题是,如何传入将随请求一起发送到服务器的字符串?

编辑:我想我可以将查询附加到请求 URL,例如“/search/?q=Something”并发送它。有人有更好的方法吗?

如果您查看有关获取的文档的 Body section,它会列出几种类型的值,您可以使用这些值来指定请求中发送的数据。

示例使用 FormData:

var fd = new FormData();
fd.append('q', 'Something');

fetch('/search', {
  method : "POST",
  body : fd
})
.then(...)

请注意,您不能在 GET 或 HEAD 请求上使用 body 选项(在您的情况下您可能正在这样做)。在这种情况下,您可以使用 URLSearchParams:

建立参数
var params = new URLSearchParams();
params.append('q', 'Something');

fetch('/search/?' + params.toString(), {
    method: 'GET'
})
.then(...);

您可以按如下方式通过

 fetch('/users', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    name: 'Hubot',
    login: 'hubot',
  })
})