Axios
Axios 是一个基于 promise 网络请求库,作用于node.js 和浏览器中。 它是 isomorphic 的(即同一套代码可以运行在浏览器和node.js中)。在服务端它使用原生 node.js http 模块, 而在客户端 (浏览端) 则使用 XMLHttpRequests。
服务器端
使用json-server
1. axios基本使用
|
|
|
axios({ |
|
method: 'GET', |
|
url: 'http://localhost:3000/posts/2' |
|
}).then(res => { |
|
console.log(res); |
|
}) |
|
|
|
|
|
axios({ |
|
method: 'POST', |
|
url: 'http://localhost:3000/posts', |
|
data: { |
|
title: 'test', |
|
author: 'lll' |
|
} |
|
}).then(res => { |
|
console.log(res); |
|
}) |
|
|
|
|
|
axios({ |
|
method: 'PUT', |
|
url: 'http://localhost:3000/posts/3', |
|
data: { |
|
title: 'test', |
|
author: 'new-lll' |
|
} |
|
}).then(res => { |
|
console.log(res); |
|
}) |
|
|
|
|
|
axios({ |
|
method: 'DELETE', |
|
url: 'http://localhost:3000/posts/3', |
|
}).then(res => { |
|
console.log(res); |
|
}) |
2. 其他请求方法
|
axios.request(config) |
|
axios.get(url[, config]) |
|
axios.delete(url[, config]) |
|
axios.head(url[, config]) |
|
axios.options(url[, config]) |
|
axios.post(url[, data[, config]]) |
|
axios.put(url[, data[, config]]) |
|
axios.patch(url[, data[, config]]) |
|
|
|
|
|
axios.request({ |
|
method: 'GET', |
|
url: 'http://localhost:3000/posts/2' |
|
}).then(res => { |
|
console.log(res) |
|
}) |
|
|
|
|
|
axios.post( |
|
'http://localhost:3000/comments', |
|
{ |
|
"body": "other", |
|
"postId": 2 |
|
} |
|
).then(res => { |
|
console.log(res) |
|
}) |
3. axios默认配置
|
|
|
axios.defaults.method = 'GET' |
|
axios.defaults.baseURL = 'http:localhost:3000' |
|
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN; |
|
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'; |
4. axios创建实例对象
|
|
|
const obj = axios.create({ |
|
baseURL: 'http://localhost:3000' |
|
}) |
|
|
|
obj({ |
|
url: 'posts/2' |
|
}).then(res => { |
|
console.log(res) |
|
}) |
5. axios拦截器
|
|
|
|
|
|
|
|
|
|
|
|
|
axios.interceptors.request.use(functio(config) { |
|
console.log('req success') |
|
return config |
|
}), function (error) { |
|
console.log('req fail') |
|
return Promise.reject(error) |
|
} |
|
|
|
|
|
axios.interceptors.response.use(functio(response) { |
|
console.log('res success') |
|
return response; |
|
}, function (error) { |
|
console.log('res fail') |
|
return Promise.reject(error); |
|
}); |
6. 取消请求
|
let cancel = nul |
|
btns[0].onclick = function () { |
|
|
|
if (cancel !== null) { |
|
cancel() |
|
} |
|
axios({ |
|
url: '/posts', |
|
cancelToken: new axios.CancelTok(function executor(c) { |
|
cancel = c; |
|
}) |
|
}).then(res => { |
|
cancel = null |
|
console.log(res) |
|
}) |
|
btns[1].onclick = function () { |
|
cancel() |
|
} |
出处:https://www.cnblogs.com/ucbb/p/17101771.html