vue+vite开启跨域

2023/6/21 vuevite

遇到报错 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.config.js

module.exports = {
  plugins: [react()],
  server: {
    port: '3000',
    proxy: {
      '/api': {
        target: 'http://localhost:8080/',
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/api/, '') // 不可以省略rewrite
      }
    }
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13

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

axois.post('/api/xxx', data)
1
最后更新时间: 2023/7/16 15:32:35