在vue中用axios設定請求攔截和響應攔截
阿新 • • 發佈:2020-07-16
import Vue from "vue"; import router from "../../src/router/index"; import axios from "axios"; // 請求攔截 axios.interceptors.request.use( config => { config.data = JSON.stringify(config.data); config.headers = { "Content-Type": "application/json", token: localStorage.getItem("token") || "" }; return config; }, error => { return Promise.reject(err); } ); // 響應攔截 攔截器 axios.interceptors.response.use( response => {
console.log(response) if (response.data.type == 'ok') { localStorage.clear() sessionStorage.clear() router.replace({ path:"/login" }); } return response; }, error => { return Promise.reject(error); } ); export default axios
請求攔截可以攜帶token等一些資訊傳送給後臺,可以在響應攔截裡面監聽後臺返回的狀態碼,進行資料處理和特定的路由跳轉