Vue Vite 设置开发环境允许跨域

Vite Vue axios About 826 words

设置

// https://vitejs.dev/config/
export default defineConfig({
  // ...
  server: {
    port: 3000,
    proxy: {
      '/api': {
        target: 'http://localhost:8000/api',
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/api/, ''),
     }
    }
  },
})

注意

使用axios时,baseURL需设置为相对路径。

import axios from "axios";
import router from "@/router";

axios.defaults.baseURL = '/api/console';

axios.interceptors.request.use((config) => {
  let token = localStorage.getItem("token");
  if (token) {
    config.headers['Authorization'] = `Bearer ${token}`;
  }
  return config;
})

axios.interceptors.response.use((response) => {
  const {status} = response;
  if (status === 401) {
    localStorage.removeItem("token");
    router.push({name: 'Login'});
  }
  return response;
})

export default axios;
Views: 187 · Posted: 2024-02-15

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb/LiteNote

扫描下方二维码关注公众号和小程序↓↓↓

扫描下方二维码关注公众号和小程序↓↓↓


Today On History
Browsing Refresh