uni-app 配置全局代理解决跨域

12,044 阅读1分钟

在manifest.json 的源码视图最下面加上以下代码

	"h5": {
	    "devServer": {
		    "disableHostCheck": true,
		    "proxy": {
			    "/h5api": {
				    // 需要被代理的后台地址
				    "target": "https://www.abnc.com/api",
				    "changeOrigin": true,
				    "secure": false,
				    "pathRewrite": {
					    "^/h5api": "/"
				    }
			       }
		       }
	        }
        }

在main.js 封装Request请求并挂载到Vue原型上

Vue.prototype.apiUrl = '/h5api';

Vue.prototype.request = function(obj) {
	var header = obj.header || {}
	if (uni.getStorageSync('token')) {
	    // 根据业务需求自行添加这行代码
		header['token'] = uni.getStorageSync("token");
	}
	uni.request({
	        // 设置请求地址 变成了 /h5api+后台路由接口 以/h5api的请求都会被代理 
		url: this.apiUrl + obj.url, 
		data: obj.data || {},
		method: obj.method || 'GET',
		header: header,
		success: res => {
		    typeof obj.success == "function" && obj.success(res)
		},
		fail: res => {
		    typeof obj.fail == "function" && obj.fail(res)
		}
	});
}

在页面使用请求

    getNotes() { 
        // 这里要使用 this.request 这个是我们在main.js 对uni.request重新封装后的方法
	this.request({
	    // 不需要写完整的地址 只需拼上后台的路由
	    url: '/appNotice/findNoticeBySysCode', 
	    success: res => {
		console.log('系统公告', res);
		this.noticeList = res.data.list;
	    }
	});
    }

最后需要注意的是 在manifest.json 里面的代理地址如果更换了话需要重启项目

重启项目

重启项目