解决vite的跨域问题

发布时间 2023-12-27 17:58:03作者: korin5

报错信息

Access to XMLHttpRequest at 'http://localhost:3000/player' from origin 'http://localhost:4000/' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

原因

vue需要配置自定义代理规则进行跨域访问

配置跨域

官方文档:https://cn.vitejs.dev/config/server-options.html#server-proxy

在vite.config.ts修改:

//vite.config.ts

export default defineConfig({
  //......
  server: {
    //......
    port: 4000,      	//vite的默认端口(别和后端冲突了)
    proxy: {
      "/api": {			//代理的请求
        target: "http://localhost:8000",	//后端的地址
        changeOrigin: true,					//开启跨域访问
        rewrite: (path) => path.replace(/^\/api/,''),	//重写前缀(如果后端本身就有api这个通用前缀,那么就不用重写)
      },
    },
  },
})

发起请求的地方:

axios.defaults.baseURL ='/api';   //配置前缀


axios.get('info')		  //这里会发送到http://localhost:4000/info

生产环境配置跨域

生产环境配置跨域,还需要编辑nginx的配置文件,在server对象中再添加一个location对象(别忘了上一个对象末尾的分号;

server {
  //......

  location /api/ {
      proxy_pass http://localhost:8000/;   //后端的地址
  }
}