VUE学习笔记(十二)-axios拦截器的配置

axios拦截器的配置

src/api/api_config.js

import axios from "axios";
import { getToken } from "@/auth/auth.service";
import { ElMessage } from 'element-plus'
axios.defaults.baseURL = "http://localhost:8080/api";
axios.defaults.headers["X-Requested-With"] = "XMLHttpRequest";
axios.defaults.headers.post["Content-Type"] = "application/json";

//拦截器
//请求拦截
axios.interceptors.request.use((option) => {
  //为请求添加token
  const jwtToken = getToken();
  if(jwtToken){
    option.headers.Authorization = `Bearer ${jwtToken}`;
  }
  return option;
});
//响应拦截
axios.interceptors.response.use(
  (res) => {
    console.log(res);
    return res;
  },
  (error) => {
    console.log(error);
    ElMessage({
        message:error.response.data.message,
        type:"error"
    })
    return error;
  }
);
export default axios;

 

posted on 2024-05-29 10:46  御行所  阅读(19)  评论(0编辑  收藏  举报

导航