uniapp H5 开发,公众号时请求跨域了,要用proxy

这个要注意,如果你请求后端时,请求methed=OPTIONS 时,表示跨域了,这个是安全验证。

需要配置 {}/manifest.json 用代理模式

 "h5" : {
        "router" : {
            "base" : "/h5",
            "mode" : "history"
        },
        "devServer" : {
            "disableHostCheck" : true,
            "proxy" : {
                "/api" : {
                    "target" : "http://localhost:8181/jdeps",
                    "changeOrigin" : true,
                    "ws" : true,
                    "pathRewrite" : {
                        "^/api" : ""
                    }
                }
            },
            "https" : false
        }
    }

request.js

const ApiUrl = '/api' 

const request = (opt) => new Promise((resolve, reject) => {

	const token = uni.getStorageSync(tokenKey) || ""
	opt = opt || {};
	opt.url = opt.url || '';
	opt.data = opt.data || null;
	opt.method = opt.method || 'POST';
	opt.header = opt.header || {
		'content-type': 'application/x-www-form-urlencoded',
		'i18n': languageKeyMap[uni.getLocale()] || uni.getLocale(),
		"x-access-token": token,
		'wxno': wxno
	};
	uni.request({
		url: ApiUrl + opt.url,
		data: {
			...opt.data
		},
		method: opt.method,
		header: opt.header,
		dataType: 'json',
success: function(res) {
			const {
				data = {}
			} = res
			if (data.code == 200) {
				resolve(data.data);
			} else {
				uni.showToast({
					title: data.msg,
					duration: 2000,
					icon: 'none',
				})

				reject(data.msg);
			}
		},
		fail: function(e) {
			uni.showToast({
				title: e,
				duration: 2000,
				icon: 'none',
			})
			reject(e);
		}
	})
})

export default {
	request
}

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值