axios默認是請求的時候不會帶上cookie的,須要經過設置withCredentials: true
來解決。javascript
首先必須設置請求頭vue
//能夠經過這種方式給axios設置的默認請求頭 axios.defaults.headers = { "Content-Type": "application/x-www-form-urlencoded" }
其次再發送以前須要處理一下數據java
// 發送請求前處理request的數據 axios.defaults.transformRequest = [function (data) { // Do whatever you want to transform the data let newData = '' for (let k in data) { newData += encodeURIComponent(k) + '=' + encodeURIComponent(data[k]) + '&' } return newData }]
你能夠截取請求或響應在被 then 或者 catch 處理以前。ios
舉個小例子:發ajax請求的時候須要有一個loading動畫,而在請求回來以後須要把loading動畫關掉,就能夠使用這個攔截器來實現。ajax
//添加請求攔截器 axios.interceptors.request.use(config => { //在發送請求以前作某事,好比說 設置loading動畫顯示 return config }, error => { //請求錯誤時作些事 return Promise.reject(error) }) //添加響應攔截器 axios.interceptors.response.use(response => { //對響應數據作些事,好比說把loading動畫關掉 return response }, error => { //請求錯誤時作些事 return Promise.reject(error) }) //若是不想要這個攔截器也簡單,能夠刪除攔截器 var myInterceptor = axios.interceptors.request.use(function () {/*...*/}) axios.interceptors.request.eject(myInterceptor)
通常會將全部的ajax請求放在一個模塊中,新建一個http.js
axios
//http.js //設置請求baseURL axios.defaults.baseURL = '/api' //設置默認請求頭 axios.defaults.headers = { "Content-Type": "application/x-www-form-urlencoded" } // 發送請求前處理request的數據 axios.defaults.transformRequest = [function (data) { let newData = '' for (let k in data) { newData += encodeURIComponent(k) + '=' + encodeURIComponent(data[k]) + '&' } return newData }] // 帶cookie請求 axios.defaults.withCredentials = true //get請求 function get(url) { return body => axios.get(url, { params: body }) } //post請求 function post(url) { return body => axios.post(url, body) } //導出使用 export const login = get('/login')
假設配合vue使用api
// 引入login模塊 import { login } from 'http' export default { methods:{ //配合 async/await使用效果更佳 async get() { try { let res = await login({ account: 'admin' }) console.log(res) } catch (e) { console.log(e) } } } }
再另外有些人可能喜歡把axios掛載到Vue的原型上,從而在子組件內能夠直接訪問的到,作法以下:cookie
Vue.prototype.$http = axios //其餘頁面在使用axios的時候直接 this.$http就能夠了除非頁面足夠簡單,否則我我的不太喜歡這種作法。app