gpt4 book ai didi

javascript - 使用 Fetch API 进行 POST 请求?

转载 作者:行者123 更新时间:2023-12-03 01:07:08 25 4
gpt4 key购买 nike

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

最佳答案

长话短说,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() 函数即可;)

关于javascript - 使用 Fetch API 进行 POST 请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39565706/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com