使用Fetch API发布POST请求? [英] POST Request with Fetch API?
本文介绍了使用Fetch API发布POST请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我知道使用新的Fetch API(此处使用ES2017的 async
/ await
),你可以制作一个GET请求如下:
I know that with the new Fetch API (used here with ES2017's async
/await
) you can make a GET request like this:
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请求?
But how do you make a POST request?
推荐答案
长话短说,Fetch还允许您传递一个对象以获得更个性化的请求:
Long story short, Fetch also allows you to pass an object for a more personalized request:
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
});
查看获取文档以获取更多好东西和陷阱:
Check out the fetch documentation for even more goodies and gotchas:
https://developer.mozilla.org / zh-CN / docs / Web / API / Fetch_API / Using_Fetch
请注意,因为您正在执行异步尝试/捕获模式,所以'我只省略了我的例子中的 then()
函数;)
Please note that since you're doing an async try/catch pattern, you'll just omit the then()
function in my example ;)
这篇关于使用Fetch API发布POST请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文