使用 Fetch API 发布请求?

新手上路,请多包涵

我知道使用新的 Fetch API(这里使用 ES2017 的 async / await )你可以像这样发出 GET 请求:

 async getData() {
    try {
        let response = await fetch('https://example.com/api');
        let responseJson = await response.json();
        console.log(responseJson);
    } catch(error) {
        console.error(error);
    }
}

但是如何发出 POST 请求呢?

原文由 Rob 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 347
2 个回答

长话短说,Fetch 还允许您传递对象以获得更个性化的请求:

 fetch("http://example.com/api/endpoint/", {
  method: "post",
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json'
  },

  //make sure to serialize your JSON body
  body: JSON.stringify({
    name: myName,
    password: myPassword
  })
})
.then( (response) => {
   //do something awesome that makes the world a better place
});

查看 fetch 文档以获取更多优点和陷阱:

https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

请注意,由于您正在执行异步 try/catch 模式,因此您只需在我的示例中省略 then() 函数;)

原文由 hellojebus 发布,翻译遵循 CC BY-SA 3.0 许可协议

如果你想发出一个简单的发布请求而不发送数据作为 JSON。

 fetch("/url-to-post",
{
    method: "POST",

    // whatever data you want to post with a key-value pair

    body: "name=manas&age=20",
    headers:
    {
        "Content-Type": "application/x-www-form-urlencoded"
    }

}).then((response) =>
{
    // do something awesome that makes the world a better place
});

原文由 manas 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题