简体   繁体   English

如何使用 Fetch API 发布身体数据?

[英]How to post body data using Fetch API?

Below is the curl command that gives back the response successfully upon importing and running in postman.下面是在postman导入运行成功返回响应的curl命令。

    curl --request POST \
--data "grant_type=password" \
--data "username=test" \
--data "password=xyz1234" \
--data "scope=write" \
--data "client_id=test" \
--data "client_secret=test12" \
"https://example.com/access_token"

Below is how I am sending data using fetch api in my js code.下面是我如何在我的 js 代码中使用 fetch api 发送数据。

       const response = await fetch ('https://example.com/access_token', 

  {
    'credentials' : 'include',
     method: 'POST',
     headers: {
      'Content-Type': 'application/json',
      },
     body: JSON.stringify({ grant_type:'password',username:'test',password:'xyz1234',scope:'write',client_id:'test',client_secret:'test12'}),
})

However the equilavent curl which is generated after copying from chrome developer tools is below.但是,从 chrome 开发人员工具复制后生成的等价物 curl 如下所示。

curl --request POST \
--data-raw '{"grant_type":"password","username":"test","password":"xyz1234","scope":"write","client_id":"test","client_secret":"test12"}'
"https://example.com/access_token"

I suspect that the body data is not constructed in the correct format.我怀疑主体数据的格式不正确。 This may be leading to a 400 error code response.这可能会导致 400 错误代码响应。 How should I send the data using fetch api equilavent to working curl command?我应该如何使用 fetch api 等同于工作 curl 命令发送数据?

Looking at the curl your data does seem to be URL encoded.查看curl您的数据似乎确实是 URL 编码的。 So as it's not expecting JSON don't serialize it to a JSON string.因此,因为它不期望 JSON 不要将它序列化为 JSON 字符串。

const headers = new Headers({
  "Content-Type": "application/x-www-form-urlencoded"
});

const urlencoded = new URLSearchParams({
  "grant_type": "password",
  "username": "test",
  "password": "xyz1234",
  "scope": "write",
  "client_id": "test",
  "client_secret": "test12",
});

const opts = {
  method: 'POST',
  headers: headers,
  body: urlencoded,
};

fetch("https://example.com/access_token", opts);

EDIT编辑

As @Kaiido mentioned in the comments.正如@Kaiido在评论中提到的那样。 It is not necessary to set the Content-Type header explicitly as the browser will do that automatically, but I have done it here to show you that it should not be set to application/json but to application/x-www-form-urlencoded .没有必要显式设置Content-Type header,因为浏览器会自动执行此操作,但我在这里这样做是为了向您展示不应将其设置为application/json ,而应设置为application/x-www-form-urlencoded .

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

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