正确配置
在根目录新建一个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跨域
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。