使用Fetch API的POST请求?

罗伯:

我知道,使用新的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请求?

hellojebus:

长话短说,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
});

查看获取文档以获取更多好处和陷阱:

https://developer.mozilla.org/zh-CN/docs/Web/API/Fetch_API/Using_Fetch

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章