axios是vue官方推荐的调用接口的方法
一、基础用法
1. axios 改写为 Vue 的原型属性
(1). 安装依赖包: npm install axios --save
(2). 全局引入:在main.js引用
import Vue from 'vue'
import axios from 'axios'
Vue.prototype.$axios = axios //全局注册
(3). 组件中调用
this.$axios({
method:'post',
url:'api',
data:{ //这里是发送给后台的数据
userId:this.userId,
token:this.token,
}
}).then((response) =>{ //这里使用了ES6的语法
console.log(response) //请求成功返回的数据
}).catch((error) =>{
console.log(error) //请求失败返回的数据
})
2. 结合 vue-axios使用
(1). 安装: npm install --save axios vue-axios
(2). 在main.js中引用
import axios from 'axios'
import VueAxios from 'vue-axios'
Vue.use(VueAxios,axios);
(3). 组件中调用
this.axios.get('api/getNewsList').then((response)=>{
this.newsList=response.data.data;
}).catch((response)=>{
console.log(response);
})
3. 封装 axios
// 第一部分:封装axios
import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
// 创建axios实例
const service = axios.create({
baseURL: process.env.BASE_API, // api的base_url
timeout: 5000 // 请求超时时间
})
// request拦截器
service.interceptors.request.use(config => {
// Do something before request is sent
if (store.getters.token) {
config.headers['X-Token'] = getToken() // 让每个请求携带token--['X-Token']为自定义key 请根据实际情况自行修改
}
return config
}, error => {
// Do something with request error
console.log(error) // for debug
Promise.reject(error)
})
// respone拦截器
service.interceptors.response.use(
response => response,
/**
* 下面的注释为通过response自定义code来标示请求状态,当code返回如下情况为权限有问题,登出并返回到登录页
* 如通过xmlhttprequest 状态码标识 逻辑可写在下面error中
*/
// const res = response.data;
// if (res.code !== 20000) {
// Message({
// message: res.message,
// type: 'error',
// duration: 5 * 1000
// });
// return Promise.reject('error');
// } else {
// return response.data;
// }
error => {
console.log('err' + error)// for debug
Message({
message: error.message,
type: 'error',
duration: 5 * 1000
})
return Promise.reject(error)
})
export default service
// 第二部分:调用
import request from '@/utils/request'
//使用
export function getInfo(params) {
return request({
url: '/user/info',
method: 'get',
params
});
}
二、参数设置(在main.js全局配置)
axios.defaults.baseURL = “http:”; // 设置统一的后台接口地址 axios.defaults.timeout = 5000; // 设置响应超时时间 axios.defaults.withCredentials = true; //允许跨域携带cookie信息 注意:设置完withCredentials可能会报错:Access to XMLHttpRequest at '...' from origin '...' has been blocked by CORS policy: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute. 原因是:前端设置withCredentials的情况下,后端要设置Access-Control-Allow-Origin为你的源地址,例如http://localhost:8080,而且还要设置header(‘Access-Control-Allow-Credentials: true’);另外,Access-Control-Allow-Origin不能设置为*,不然cookie不会出现在http的请求头里,所以报错里说Access-Control-Allow-Origin不能是*。 axios.defaults.headers['Content-Type'] = ‘application/x-www-form-urlencoded'; //请求头参数设置