赞
踩
uni-app 配置代理 vue.config.js无效的问题 本文通过vite.config.js解决
之前在网上搜了很多配置,比如manifest.json 配置H5跨域请求、vue.config.js配置通通无效,例如下面这个:也是无效
错误示例manifest.json:
- "h5" : {
- "devServer" : {
- "https" : false,
- "proxy" :{
- "/api":{
- "target":"http://localhost:4000",
- "changeOrigin":true,
- "secure":false,
- "pathRewrite":{
- "^/api" : ""
- }
- }
- }
- }
- }
错误示例vue.config.js:
- module.exports = {
- devServer: {
- proxy: {
- '/api': {
- target: 'http://localhost:8080/api',
- changeOrigin: true,
- pathRewrite: {
- '^/api': ''
- }
- }
- },
- }
- }
正确示例:
经过本人多番查找问题总算找到了合适的方法,使用以下配置:(也有版本问题后面会讲):
- import {
- defineConfig
- } from "vite"
- import uni from "@dcloudio/vite-plugin-uni";
-
- export default defineConfig({
- plugins: [
- uni()
- ],
- server: {
- proxy: {
- '/api': {
- target: 'http://localhost:4000',
- changeOrigin: true,
- rewrite: path => path.replace(/^\/api/, '')
- },
-
- }
- }
- })

这套配置可能在网上很多人发,但是都会报错不是这个错误就那个错误,比如这个错误:
Error: Cannot find module '../../../uni-cli-shared/dist'
- 17:16:59.289 failed to load config from xxx/vite.config.js
- 17:16:59.308 error when starting dev server:
- 17:16:59.308 Error: Cannot find module '../../../uni-cli-shared/dist'
等等之类的,我踩过太多了坑了..后来我发现是@dcloudio/vite-plugin-uni版本问题,需要安装指定版本
并且删除manifest.json的所有跨域配置(manifest.json优先级比较高)
- {
- "dependencies": {
- "@dcloudio/vite-plugin-uni": "^3.0.0-alpha-4010820240517001",
- "ant-design-vue": "^4.2.1",
- "axios": "^1.6.8",
- "axios-adapter-uniapp": "^0.1.4",
- "echarts": "^5.5.0",
- "mpvue-echarts": "^1.0.0",
- "vite": "^5.2.11"
- }
- }
yarn add @dcloudio/vite-plugin-uni@3.0.0-alpha-4010820240517001
然后总算解决了这个问题
如果对你有帮助的话点个赞.谢谢了
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。