异步组件。
参考:
- 官方文档
- 看云axios中文文档
基础
安装
npm install axios
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
基础api
axios.get(url[, config])axios.delete(url[, config])axios.post(url[, data[, config]])axios.put(url[, data[, config]])axios.patch(url[, data[, config]])
get请求
axios.get('/user', {params: {ID: 12345}}).then(function (response) {console.log(response);}).catch(function (error) {console.log(error);});
post请求
axios.post('/user', {firstName: 'Fred',lastName: 'Flintstone'}).then(function (response) {console.log(response);}).catch(function (error) {console.log(error);});
完整参数
axios({method: 'post',url: '/user/12345',data: {firstName: 'Fred',lastName: 'Flintstone'}});
拦截器
// 添加请求拦截器axios.interceptors.request.use(function (config) {/*添加token*/let token = localStorage.getItem("x-auth-token"); // 给所有请求带上tokenif (token) { // 判断是否存在token,如果存在的话,则每个http header都加上tokenconfig.headers.token = `${token}`;}return config;}, function (error) {// 对请求错误做些什么return Promise.reject(error);});// 添加响应拦截器axios.interceptors.response.use(function (response) {// 对响应数据做点什么return response.data;}, function (error) {// 对响应错误做点什么return Promise.reject(error);});
form形式传递数据
参考:csdn
post默认是json形式,后台必须使用requestbody接收,如果要使用传统form形式,改怎么办呢?
qs其实是querystring的缩写,会url格式化。
引用
<script src="//cdn.bootcss.com/qs/6.5.2/qs.min.js"></script>注意,这种方式引用要使用:Qs.stringify
使用
axios.post('/foo', qs.stringify({ 'bar': 123 }));
和JSON的区别:

全局默认配置
这个使用不多
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";axios.defaults.headers.common['Authorization'] = ''; // 设置请求头为 Authorizationaxios.defaults.timeout = 200;// 跨域处理cookie等权限axios.defaults.withCredentials = true
异步执行顺序解决方案
有些时候,我们异步有执行顺序的要求。
使用return

使用await
函数内同步,函数外异步。
示例一
// async/await version:async function asyn_run(){let v1 = await promise1();let v2 = await promise2(v1);let v3 = await promise3(v1, v2);/*... v1, v2, v3 ... */}async_run(); //actually non-blocking
示例二:
let user = {id: 1};async function init() {let a = await axios.post("http://httpbin.org/post", user).then(res => {user.id = 2;return 123;});console.log(a); // 这个时候a=123let b = await axios.post("http://httpbin.org/post", user).then(res=>{console.log(res.data);})}init();
