使用vite创建项目,配置代理跨域,需要在vite.config.js的文件中,去配置。

这是使用vite搭建项目vite.config.js文件初始化的样子

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [vue()],//使用vue插件。
  resolve: {
    alias: {
      "@": fileURLToPath(new URL("/src", import.meta.url))
    }
  },//通过@符,来快速找到src文件。不用使用相对路径来找来找去。
})

下面通过server来配置

export default defineConfig({
  plugins: [vue()],//使用vue插件。
  resolve: {
    alias: {
      "@": fileURLToPath(new URL("/src", import.meta.url))
    }
  },//通过@符,来快速找到src文件。不用使用相对路径来找来找去。
  server: {
    port:4000,//设置服务启动端口号,是一个可选项,不要设置为本机的端口号,可能会发生冲突
    open:true,//是否自动打开浏览器,可选项
    cors:true,//允许跨域。
    // 设置代理
    proxy: {
      // 将请求代理到另一个服务器
      '/api': {
        target: 'https://alloyteam-api.onrender.com/',//这是你要跨域请求的地址前缀
        changeOrigin: true,//开启跨域
        rewrite: path => path.replace(/^\/api/, ''),//去除前缀api
      }
    }
  }
})

这是配置跨域代理之后的vite.config.js的文件。然后通过axios去请求数据。

Logo

前往低代码交流专区

更多推荐