Vite中跨域配置

19,221 阅读1分钟

遇到报错 Access to XMLHttpRequest at xx from origin xx has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

在vite中如何处理跨域问题呢?

首先打开vite.config.js

修改配置如下:

module.exports = {
  plugins: [react()],
  server: {
    port: '3000',
    proxy: {
      '/api': {
        target: 'http://localhost:8080/',
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/api/, '') // 不可以省略rewrite
      }
    }
  }
}

这里的 '/api' 指的是你想代理的请求,而target则是你所想请求的后端地址。 新手最容易出现的问题就是localhost:3000去请求localhost:8080,那么在target处应该填写8080.

最后,在实际请求方法中,你可以写成如下代码

axois.post('/api/xxx', data)