UniApp 中 Web/H5 正确使用反向代理解决跨域问题

前端 0

因为 Vue3 的构建工具是 Vite,所以配置 vue.config.js 是没用的(Vue2 因为使用 webpack 所以才用这个文件)

这里提供一份 vue.config.js 的示例:

module.exports = {    devServer: {        proxy: {            '/api': {                target: 'http://example.com',                changeOrigin: true,                pathRewrite: {                    '^/api': '/',                },            }        }    }}

同时 manifest.json 里配置的反代配置似乎有 Bug,反代能生效,但 path 重写是失效的,即:

{    "h5": {        "devServer": {            "https": false,            "disableHostCheck": true,            "proxy": {                "/api": {                    "target": "http://example.com",                    "pathRewrite": {                        "^/api": ""                    }                }            }        }    }}

因为使用了 Vite,所以我们应该创建 vite.config.js 文件进行设置:

import { defineConfig } from 'vite';import uni from '@dcloudio/vite-plugin-uni';export default defineConfig({    plugins: [        uni()    ],    server: {        host: '127.0.0.1',        port: 5173,        proxy: {            '/api': {                target: 'http://example.com',                changeOrigin: true,                rewrite: (path) => path.replace(/^//api/, ''), // 此处进行路径重写            }        }    }});

至此重新运行服务即可看到生效并成功的反向代理,更多关于 Vite 反代配置看这里:https://cn.vitejs.dev/config/server-options#server-proxy

也许您对下面的内容还感兴趣: