简体   繁体   English

Web API 获取请求正文未定义

[英]Web API Fetch Request body is undefined

I was going through the docs of the Request interface in Fetch API https://developer.mozilla.org/en-US/docs/Web/API/Request我在 Fetch API https://developer.mozilla.org/en-US/docs/Web/API/Request中浏览了 Request 接口的文档

The example where we set the body does not seem to work.我们设置主体的示例似乎不起作用。 Tried on chrome dev console (version 84.0.4147.89) and also on firefox (84.0).在 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);

This results in,这导致,

https://example.com/
POST
undefined

What am I doing wrong here...?我在这里做错了什么......?

EDIT:编辑:

The following is working,以下工作,

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

This leads me to believe that the body was set, but the getter is not working for some reason.这让我相信身体已经设置好了,但是吸气剂由于某种原因没有工作。

Can anyone shed light on what's going on?任何人都可以阐明发生了什么吗?

Try the following example:试试下面的例子:

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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM