2021年的答案:以防你在这里找如何使用async/await或promises与axios相比制作GET和POST Fetch api请求的方法。
我使用jsonplaceholder假API演示:
使用async/await进行Fetch api GET请求:
const asyncGetCall = async () => {
try {
const response = await fetch('https://jsonplaceholder.typicode.com/posts');
const data = await response.json();
console.log(data);
} catch(error) {
console.log(error)
}
}
asyncGetCall()
使用async/await进行Fetch api的POST请求:
const asyncPostCall = async () => {
try {
const response = await fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
title: "My post title",
body: "My post content."
})
});
const data = await response.json();
console.log(data);
} catch(error) {
console.log(error)
}
}
asyncPostCall()
使用 Promises 发送 GET 请求:
fetch('https://jsonplaceholder.typicode.com/posts')
.then(res => res.json())
.then(data => {
console.log(data)
})
.catch(error => {
console.log(error)
})
使用Promise进行POST请求:
fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
title: "My post title",
body: "My post content."
})
})
.then(res => res.json())
.then(data => {
console.log(data)
})
.catch(error => {
console.log(error)
})
Axios 使用 GET 请求:
const axiosGetCall = async () => {
try {
const { data } = await axios.get('https://jsonplaceholder.typicode.com/posts')
console.log(`data: `, data)
} catch (error) {
console.log(`error: `, error)
}
}
axiosGetCall()
使用 Axios 发送 POST 请求:
const axiosPostCall = async () => {
try {
const { data } = await axios.post('https://jsonplaceholder.typicode.com/posts', {
title: "My post title",
body: "My post content."
})
console.log(`data: `, data)
} catch (error) {
console.log(`error: `, error)
}
}
axiosPostCall()
async
/await
和 (完全独立的) Fetch API。你的问题与 JavaScript 的async
/await
没有任何关系,而是关于fetch
。另外请注意,新的 Fetch API 是新的,因此仅支持最先进的浏览器。 - T.J. Crowder