uniapp 或者Vue2和3 的跨域接口问题

uniapp 的H5端跨域问题

这个是Vue2 的跨域代理
1.1 在manifest.json 里添加H5的跨域代理
这个配置是多个host 接口的
"h5": {
        "devServer": {
            "disableHostCheck": true,  //禁用主机名检查会降低安全性,因为它允许来自任何主机的请求
            "proxy": {
                "/api01": {
                    "target": "第二个服务器地址",
                    "changeOrigin": true,
                    "secure": false,
                    "ws": false,
                    "pathRewrite": {
                        // "^/api": ""表示将请求路径中的/api前缀移除。例如,/api/users会被重写为/users
                        "^/api01": ""
                    }
                },
                "/api02": {
                    "target": "第二个服务器地址", // 目标服务器地址,需要  填写
                    "changeOrigin": true, // 是否修改请求头中的host字段为target服务器的host
                    "secure": false, // 是否验证代理服务器的SSL证书
                    "ws": false, // 是否代理WebSocket
                    "pathRewrite": {
                        "^/api02": "" // 重写请求路径,移除/ 前缀  例如,/api/gpt会被重写为/gpt
                    }
                }
            }
        }
    }

1.2 在项目的根目录下创建 vue.config.js 编辑器会自动检测使用
优先级是 manifest.json> vue.config.js 的配置
module.exports = {
    devServer: {
        disableHostCheck: true,
        proxy: {
            "/api": {
                    "target": "目标服务器地址", // 目标服务器地址,需要  填写
                    "changeOrigin": true, // 是否修改请求头中的host字段为target服务器的host
                    "secure": false, // 是否验证代理服务器的SSL证书
                    "ws": false, // 是否代理WebSocket
                    "pathRewrite": {
                        "^/api": "" // 重写请求路径,移除/ 前缀  例如,/api/gpt会被重写为/gpt
                    }
            }
        }
    }
}

这个是Vue3 的跨域代理
1.3 在项目的根目录下创建 vite.config.js 编辑器会自动检测使用
import { defineConfig } from 'vite';
import uni from '@dcloudio/vite-plugin-uni';
export default defineConfig({
  plugins: [uni()],
  server: {
    host: "localhost", // 指定服务器应该监听哪个IP地址,默认:localhost
    port: 5173,        // 指定开发服务器端口,默认:5173
    proxy: {           // 为开发服务器配置自定义代理规则
       // 带选项写法:http://localhost:5173/api/posts -> http://jsonplaceholder.typicode.com/posts
      "/baiduapi": {
        target: "https://aip.baidubce.com", // 目标接口
        changeOrigin: true,            // 是否换源
        rewrite: (path) => path.replace(/^\/baiduapi/, ""),
      }
    }
  }
});

1.4 在uniapp 上的接口的使用
import { defineConfig } from 'vite';
import uni from '@dcloudio/vite-plugin-uni';
export default defineConfig({
  plugins: [uni()],
  server: {
    host: "localhost", // 指定服务器应该监听哪个IP地址,默认:localhost
    port: 5173,        // 指定开发服务器端口,默认:5173
    proxy: {           // 为开发服务器配置自定义代理规则
      "/baiduapi": {
        target: "https://aip.baidubce.com", // 目标接口
        changeOrigin: true,            // 是否换源
        rewrite: (path) => path.replace(/^\/baiduapi/, ""),
      }
    }
  }
});

1.4 跨域的问题 个人经验总结

H5上才有跨域问题    前端代理解决 和 后端解决等
在APP 端是不用考虑跨域问题的 

如有不正确请告知 嘿嘿

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容