uniapp H5本地开发产生跨域处理

2,225 阅读1分钟

小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。

开发配置权重

可以修改manifest.json配置信息, uni-app 中 manifest.json->h5->devServer 实际上对应 webpack 的 devServer,鉴于 manifest 为 json 文件,故 webpack.config.js->devServer 配置项下的简单类型属性均可在manifest.json->h5->devServer节点下配置,funciton 等复杂类型暂不支持。

页面路由模式是history依赖后端配置返回

{
  "h5": {
  "router": {
    "mode":"history" // hash 使用 URL 的 hash 来模拟一个完整的 URL,于是当 URL 改变时,页面不会重新加载。|| history 
  },
  "devServer": {  
    "https": false, // 是否使用https协议
    "host": "0.0.0.0",  
    "hotOnly": true,
    "port": 8000,  
    "disableHostCheck": true,
    "proxy": {  
      "/api": {  
        "target": "https://xxx.xxx.cn",    // API服务器的地址
        "changeOrigin": true,   
        "secure": true,   // 设置支持https协议的代理
        "ws": true,       // 代理websockets
        "pathRewrite": {  // 重写路径 比如'/api/user/info'重写为'/user/info', target+pathRewrite
          "^/api": ""  
        }
      }  
    }  
  }  
  },
}

开发环境中manifest.json proxy的pathRewrite将"/api"替换成空,下面是请求接口

let baseUrl = ""

// 根据环境变量设置接口地址
switch(process.env.NODE_ENV){
    case "development":
        baseUrl = '/api';
        break;
    case "production":
        baseUrl = 'xxx.xxx.com';
        break;
    default:
        baseUrl = "其他环境"
}

uni.requset({
    url: baseUrl+"/api/user/info"
    method:"post",
})

uniapp的工具函数promisic

uniapp的接口采用回调函数的方式作为返回值,所以下面有一个工具函数,将uniapp的api的success和fail返回promise

使用方式promisic(wx.request)({url:""}).then(res).catch(err); 或者 let res = await promisic(wx.request)({url:""});

 /** 将小程序的回调函数转化promise形式
  * @description: 
  * @param {Function} func
  * @return {Promise}
  */	
function promisic (func) {
    return function (params = {}) {
        return new Promise((resolve, reject) => {
            const args = Object.assign(params, {
                success: (res) => {
                    resolve(res);
                },
                fail: (error) => {
                    reject(error);
                }
            });
            func(args);
        });
    };
}