【Vue】前端解决跨域问题——反向代理

在 axios 请求路径只需填写资源路径:

axios.get('/adminapi/users').then(res => {
  console.log(res)
})

此时相当于向自己发送请求,会报 404。

然后在 vue.config.js 中配置反向代理:

const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
  transpileDependencies: true,
  lintOnSave: false, /*关闭语法检查*/
  // 配置反向代理
  devServer: {
    proxy: {
      // /adminapi/* - 后台管理使用
      // /webapi/* - 企业官网使用
      '/adminapi': {
        target: 'http://localhost:3000',   // 此时后端是 3000
        changeOrigin: true,
      }
    }
  }
})

或者使用 vite.config.js :

import {fileURLToPath, URL} from 'node:url'
import {defineConfig} from 'vite'
import vue from '@vitejs/plugin-vue'

// https://vitejs.dev/config/
export default defineConfig({
    plugins: [
        vue(),
    ],
    resolve: {
        alias: {
            '@': fileURLToPath(new URL('./src', import.meta.url))
        }
    },
    server: {
        proxy: {
        	// 讲解:如果请求路径为 http://localhost:5173/api/xxx
        	// 1. 先换源,http://localhost:8080/api/xxx 为后端的源
        	// 2. 再重写 /api 为空,http://localhost:8080/xxx  反向代理成功
            '/api': {  // 如果请求路径含有 /api
                target: 'http://localhost:8080',  // target 将源更换为这个,此时后端是 8080
                changeOrigin: true,  // 是否改变域
                rewrite: (path) => path.replace(/^\/api/, ''),  // 将 '/api' 重写为 ''
            }
        }
    }
})

利用反向代理将请求转发出去。

在这里插入图片描述

请求成功!

当然最好还是跟着官方文档走 :代理跨域

import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
// 引入svg需要用到的插件
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
import path from 'path'
// mock 插件提供方法
import { viteMockServe } from 'vite-plugin-mock'
// https://vitejs.dev/config/
export default defineConfig(({ command,mode }) => {
  // 获取各种环境下的对应的变量 mode模式默认为开发环境, process.cwd()为项目根目录(即index.html所在的位置)
  const env = loadEnv(mode, process.cwd())
  return {
    plugins: [vue(),
    createSvgIconsPlugin({
      iconDirs: [path.resolve(process.cwd(), 'src/assets/icons')],
      symbolId: 'icon-[dir]-[name]',
    }),
    viteMockServe({
      localEnabled: command === 'serve',
    }),
    ],
    resolve: {
      alias: {
        "@": path.resolve("./src") // 相对路径别名配置,使用 @ 代替 src
      }
    },
    // scss 全局变量的配置
    css: {
      preprocessorOptions: {
        scss: {
          javascriptEnabled: true,
          additionalData: '@import "./src/styles/variable.scss";',
        },
      },
    },
    // 代理跨域
    server: {
      proxy: {
        [env.VITE_APP_BASE_API]: {
          // 获取数据的服务器地址
          target: env.VITE_APP_BASE_API,
          // 是否代理跨域
          changeOrigin: true,
          // 路径重写
          rewrite: (path) => path.replace(/^\/api/, ''),
        }
      }
    }
  }
})

env 文件见 :环境变量配置

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小秀_heo

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值