Vue:對axios進行簡單的二次封裝


主要做3點:

1、配置一個請求地址前綴

2、請求攔截(在請求發出去之前攔截),給所有的請求都帶上 token

3、攔截響應,遇到 token 不合法則報錯

// 對 axios 的二次封裝
import axios from 'axios'
import router from '../router' // 引入路由對像,用於路由跳轉

// 創建一個新的 axios 實例
axios.defaults.withCredentials = true //解決跨域后如何在請求里帶上cookie的問題
var http = axios.create({
  baseURL: 'http://localhost:8080/',
  timeout: 8000, // 請求超時
})

// 請求攔截(在請求發出去之前攔截),給所有的請求都帶上 token
http.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('token')
    if (token) {
      // 設置 token ,一般是在 headers 里加入 Authorization,並加上 Bearer 標注
      // 最好通過此種形式設置 request.headers['Authorization']
      config.headers['Authorization'] = token
    }
    return config
  },
  (error) => {
    console.log(error)
    return Promise.reject(error)
  }
)

// 攔截響應,遇到 token 不合法則報錯
http.interceptors.response.use(
    response => {
        if (response.data.token) { // 將返回的最新的 token 保存
            localStorage.setItem('token', response.data.token);
        }
        return response;
    },
    error => {
        if (error.response.status === 401) {
            // 401 說明 token 驗證失敗
            // 可以直接跳轉到登錄頁面,重新登錄獲取 token
            localStorage.removeItem('token');
            console.log(error.response.data.error.message);
            router.replace({
                path: '/login',
                query: {
                    redirect: router.currentRoute.fullPath
                }
            })
        } else if (error.response.status === 500) {
            // 服務器錯誤
            return Promise.reject('服務器出錯:', error.response.data);
        }
        return Promise.reject(error.response.data); // 返回接口返回的錯誤信息
    });

export default http

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM