建议
我这里只是列出了一些简单的知识点,方便我的记忆回顾。
建议看 sass 官方文档,里面的内容更加详细和完善,内容也是最新的,网址:https://www.axios-http.cn/docs/intro。
安装
使用 npm:$ npm install axios
使用 cdn:<script src="https://unpkg.com/axios/dist/axios.min.js"></script>(可以在 https://www.bootcdn.cn/ 网站去获取 cdn)
使用 bower:$ bower install axios
使用 yarn:yarn add axios
引入 axios
为了在CommonJS中使用 require() 导入时获得TypeScript类型推断(智能感知/自动完成),请使用以下方法:
const axios = require('axios').default
|
axios.<method> 能够提供自动完成和参数类型推断功能
GET 请求
GET 请求的参数可以跟在 url 后面,如:?name='张三'&age=18 。也可以放在第二个参数位,使用 params 请求体,以键值对的形式进行请求。
axios.get('/user?ID=12345')
axios.get('/user', { params: { ID: 12345 } })
axios.get().then().catch()
async function getUser() { try { const response = await axios.get('/user?ID=12345') } catch (err) { console.error(err) } }
|
POST 请求
POST 请求只能在第二个参数位,以键值对的形式进行请求。
axios.post('/user', {}).then().catch()
|
执行多个并发请求
function getUserAccount() { return axios.get('/user/12345') }
function getUserPermissions() { return axios.get('/user/12345/permissions') }
axios.all([getUserAccount(), getUserPermissions()]).then()
|
axios API
可以通过向 axios 传递相关配置来创建请求
**语法**:axios(config) (config:配置对象)
**语法**:axios(url[, config])(默认是发送 GET 请求)
axios({ method: 'post', url: '/user/12345', data: { firstName: 'Fred', lastName: 'Flintstone' } }).then()
axios({ method:'get', url:'http://bit.ly/2mTM3nY', responseType:'stream' }).then()
|
并发
处理并发请求的函数
axios.all(iterable)
axios.spread(callback)
建实例对象
可以使用自定义配置新建一个 axios 实例。axios.create([config])
语法:
const test = axios.create({ baseURL: 'http://127.0.0.1:8000', timeout: 1000, headers: {'X-Custom-Header': 'foobar'} });
test({ url: '/server' }).then()
test.get('/server').then()
|
实例方法:
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]])
注意:在使用别名方法时, url、method、data 这些属性都不必在配置中指定。
axios.request({ method: 'GET', url: '' }).then()
axios.post('url',{}).then()
|
请求配置
这些是创建请求时可以用的配置选项。只有 url 是必需的。如果没有指定 method,请求将默认使用 GET 方法。
{ url: '/user', method: 'get', baseURL: 'https://some-domain.com/api/', headers: {'X-Requested-With': 'XMLHttpRequest'}, timeout: 1000, params: { ID: 12345 },
data: { firstName: 'Fred' }, transformRequest: [function (data, headers) { return data; }],
transformResponse: [function (data) { return data; }],
auth: { username: 'janedoe', password: 's00pers3cret' },
responseType: 'json',
onUploadProgress: function (progressEvent) { },
onDownloadProgress: function (progressEvent) { }, proxy: { protocol: 'https', host: '127.0.0.1', port: 9000, auth: { username: 'mikeymike', password: 'rapunz3l' } },
}
|
响应结构
服务器返回的响应信息:
{ data: {}, status: 200, statusText: 'OK',
headers: {},
config: {},
request: {} }
|
当使用 then 时,您将接收如下响应:
axios.get('/user/12345') .then(function (response) { console.log(response.data); console.log(response.status); console.log(response.statusText); console.log(response.headers); console.log(response.config); })
|
默认配置
全局 axios 默认配置:
axios.defaults.baseURL = 'https://api.example.com';
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN; axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
|
自定义实例默认值:
const instance = axios.create({ baseURL: 'https://api.example.com' });
instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;
|
axios({ method:'GET', url:'http://127.0.0.1:8000/server', data:{ xxx } ).then()
axios.default.method = 'GET'
axios.default.baseURL = 'http://127.0.0.1:8000'
axios.default.params = {id:100}
axios.default.timeout = 3000
|
拦截器
在请求或响应被 then 或 catch 处理前拦截它们。
axios.interceptors.request.use(function (config) { return config; }, function (error) { return Promise.reject(error); });
axios.interceptors.response.use(function (response) { return response; }, function (error) { return Promise.reject(error); })
|
如果你想在稍后移除拦截器,可以这样:
const myInterceptor = axios.interceptors.request.use(function () {}); axios.interceptors.request.eject(myInterceptor);
|
可以为自定义 axios 实例添加拦截器
const instance = axios.create(); instance.interceptors.request.use(function () {});
|