ajax axios fetch 请求方法对比

axios:
axios.post(url[, data[, config]])
axios.get(url[, config])

axios({
method:’get’,
url:’http://bit.ly/2mTM3nY’,
responseType:’stream’
})
.then(function (response) {
response.data.pipe(fs.createWriteStream(‘ada_lovelace.jpg’))
});

fetch:
fetch(url, {config})
.then(
if (response.ok) {
return response.json()
} else {
// Find some way to get to execute .catch()
return Promise.reject(‘something went wrong!’)
}
)
.then(data => console.log(‘data is’, data))
.catch(error => ({ error }));

0. 断网 // 只会走catch 函数
以下都会走then
1. 可能尝试获取不存在的资源 404
2. 没有权限获取资源
3. 输入参数有误
4. 服务器抛出异常
5. 服务器超时
6. 服务器崩溃
7. API更改 …

[cc lang=”javascript”]
// 返回消息 response 对象
{
body: ReadableStream
bodyUsed: false
headers: Headers
ok : true
redirected : false
status : 200
statusText : “OK”
type : “cors”
url : “http://some-website.com/some-url”
__proto__ : Response
}
// response.json() | response.text() | response.blob() 等这些方法都返回promise
[/cc]

Leave a Reply

Your email address will not be published. Required fields are marked *