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)
})
使用 Promises 发送 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()
{}
。 - Kaushikres.json()
应返回{a: 1, b: 2}
。 - Razorres
的值,此时您的 Promise 对象不在那里。因此,这个fetch
可能会有成功方法。这可能有效。 ;) - Kaushikjson
属性了。然而,body
也没有被正确处理。请查看此 fiddle,以查看 5 秒延迟被跳过的情况:http://jsfiddle.net/99arsnkg/ 此外,当您尝试添加其他标头时,它们会被忽略。这可能是fetch()
本身的问题。 - boombox