axios是基于promise用于浏览器和node.js的http客户端。
axios的作用是什么呢:axios主要是用于向后台发起请求的,还有在请求中做更多是可控功能。有以下特点:支持浏览器和node.js、支持promise、能拦截请求和响应、能转换请求和响应数据、能取消请求、自动转换JSON数据、浏览器端支持防止CSRF(跨站请求伪造)
promise是什么:是一个对象用来传递异步操作的信息,它代表了某个未来才会知道结果的事件(通常是一个异步操作),并且这个事件提供统一的api,可供进一步的处理。promise的作用:Promise的出现主要是解决地狱回调的问题,比如你需要结果需要请求很多个接口,这些接口的参数需要另外那个的接口返回的数据作为依赖,这样就需要我们一层嵌套一层,但是有了Promise 我们就无需嵌套。promise的本质是什么:分离异步数据获取和业务
1、axios基础用法
1.1、get请求demo
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| // 为给定 ID 的 user 创建请求 axios.get('/user?ID=12345') .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); });
// 可选地,上面的请求可以这样做 axios.get('/user', { params: { ID: 12345 } }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); });
|
1.2、post请求demo
1 2 3 4 5 6 7 8 9 10
| axios.post('/user', { firstName: 'Fred', lastName: 'Flintstone' }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); });
|
1.3、执行多个并发请求
1 2 3 4 5 6 7 8 9 10 11 12
| function getUserAccount() { return axios.get('/user/12345'); }
function getUserPermissions() { return axios.get('/user/12345/permissions'); }
axios.all([getUserAccount(), getUserPermissions()]) .then(axios.spread(function (acct, perms) { // 两个请求现在都执行完成 }));
|
1.4、API
1.4.1 请求配置
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| axios.get('/user', { params: { ID: 12345 }, // `timeout` 指定请求超时的毫秒数(0 表示无超时时间) // 如果请求话费了超过 `timeout` 的时间,请求将被中断 timeout: 1000, // `withCredentials` 表示跨域请求时是否需要使用凭证 withCredentials: false, // 默认的 // 'proxy' 定义代理服务器的主机名称和端口 // `auth` 表示 HTTP 基础验证应当用于连接代理,并提供凭据 // 这将会设置一个 `Proxy-Authorization` 头,覆写掉已有的通过使用 `header` 设置的自定义 `Proxy-Authorization` 头。 proxy: { host: '127.0.0.1', port: 9000, auth: : { username: 'mikeymike', password: 'rapunz3l' } } }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); });
|
1.4.2 响应结构
1 2 3 4 5 6 7 8 9 10 11 12
| { // `data` 由服务器提供的响应 data: {}, // `status` 来自服务器响应的 HTTP 状态码 status: 200, // `statusText` 来自服务器响应的 HTTP 状态信息 statusText: 'OK', // `headers` 服务器响应的头 headers: {}, // `config` 是为请求提供的配置信息 config: {} }
|
1.5 全局的 axios 默认值
1 2 3 4
| axios.defaults.timeout = 2000; 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';
|
2、axios和vue结合
2.1 get
1 2 3 4 5 6 7 8
| const SERVERIP = ""; export const apiLogin = (userid, password) => { return axios.get(`${SERVERIP}/api/login/login?userid=${userid}&password=${password}`); } import { apiLogin } from "./api/api.js"; apiLogin(this.userid, this.pwd).then(res => { });
|
2.2 post
1 2 3 4 5 6 7 8 9 10 11 12 13
| const SERVERIP = ""; export const updateUserPwd = (params) => { return axios({ method: 'post', url: `${SERVERIP}/api/user/update`, data: params }) } import { apiLogin } from "./api/api.js"; obj = JSON.stringify(obj); updateUserPwd(obj).then(res => { });
|
3、同步实现
3.1 、简单模式实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| getBu();
function chinaCity(){ // return axios.get('./lib/chinaCity.json') return axios.get('./lib/chinaCity.json',{ params:{ //传值模式 id:222 } }) }
async function getBu(){ var data = await chinaCity(); console.log(data) }
|
3.1 、常用模式
1 2 3 4 5 6 7 8 9 10 11
| const SERVERIP = ""; export const apiLogin = (userid, password) => { return axios.get(`${SERVERIP}/api/login/login?userid=${userid}&password=${password}`); } import { apiLogin } from "./api/api.js"; methods: { async myLogin(){ var res = await apiLogin(this.userid, this.pwd); console.log(res.data) } }
|