【问题标题】:Web API Fetch Request body is undefinedWeb API 获取请求正文未定义
【发布时间】:2020-12-19 19:48:50
【问题描述】:

我正在浏览 Fetch API 中请求接口的文档 https://developer.mozilla.org/en-US/docs/Web/API/Request

我们设置主体的示例似乎不起作用。在 chrome 开发控制台(版本 84.0.4147.89)和 Firefox(84.0)上试过。

const request = new Request('https://example.com', {method: 'POST', body: '{"foo": "bar"}'});
console.log(request.url);
console.log(request.method);
console.log(request.body);

这会导致,

https://example.com/
POST
undefined

我在这里做错了什么...?

编辑:

以下工作正常,

request.json().then((j)=>{console.log(j)});

这让我相信 body 已经设置好了,但是 getter 由于某种原因没有工作。

谁能解释发生了什么?

【问题讨论】:

标签: javascript fetch-api webapi


【解决方案1】:

试试下面的例子:

const requestOptions = {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json'
    },
    body: JSON.stringify({
        foo: 'bar'
    })
}
const response = await fetch('https://example.com', requestOptions)
const result = await response.json();

【讨论】:

  • 这行得通,我可以使用fetch(url, options) 提出请求,实际上这就是我最终要做的。但我特别想知道为什么 Request.body 没有按预期工作。
  • body 不能接受object 作为值,所以我们需要将object 通过JSON.stringify() 转换为stringdeveloper.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
猜你喜欢
  • 2016-01-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-13
  • 1970-01-01
  • 2023-04-10
相关资源
最近更新 更多