正确配置

在根目录新建一个vite.config.js文件

// vite.config.js
import {
  defineConfig
} from 'vite'
import uni from '@dcloudio/vite-plugin-uni' //官方内置的,不用下载,下面代码粘贴直接用即可
 
export default defineConfig({
  plugins: [
    uni()
  ],
  server: {
    proxy: {
      '/api': {
        target: 'https://xxx/xxxx', // 目标服务  
        changeOrigin: true,
        rewrite: path => path.replace(/^\/api/, ''),
      }
    }
  }
})

然后通过uniapp.request请求即可,记住baseurl要跟'/api'匹配。

错误配置

网上很多写法都是错误的,我在这里例举几个:
1、在根目录新建vue.config.js文件

// vue.config.js
module.exports = {
    devServer: {
            proxy: {
              '/api': {
                target: 'https://xxxx/xxxx',
                changeOrigin: true,
                pathRewrite: {
                  '^/apih5': ''
                }
              }
            },
    }
}
在vue3+h5版本无效

2、在mainfest.json文件中配置跨域代理

// manifest.json
{
    "h5": {
        "devServer": {
            "proxy": {
                 '/api': {
                    target: 'https://xxxxx/xxxx',
                    changeOrigin: true,
                    pathRewrite: {
                      '^/apih5': ''
                    }
                  }
            }
        }
    }
}
亲测无效,配置后依旧提示404跨域

兔子先森
482 声望558 粉丝

致力于新技术的推广与优秀技术的普及。