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

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

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

javascript 复制代码
 "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

javascript 复制代码
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
}
相关推荐
局外人LZ19 小时前
Uniapp脚手架项目搭建,uniapp+vue3+uView pro+vite+pinia+sass
前端·uni-app·sass
2501_9159184121 小时前
在 iOS 环境下查看 App 详细信息与文件目录
android·ios·小程序·https·uni-app·iphone·webview
前端呆头鹅21 小时前
Websocket使用方案详解(uniapp版)
websocket·网络协议·uni-app
浮桥1 天前
uniapp+h5 公众号实现分享海报绘制
uni-app·notepad++
2501_916007471 天前
没有 Mac 用户如何上架 App Store,IPA生成、证书与描述文件管理、跨平台上传
android·macos·ios·小程序·uni-app·iphone·webview
wangjun51591 天前
uniapp uni.downloadFile 偶发性下载文件失败 无响应
uni-app
2501_915106322 天前
当 Perfdog 开始收费之后,我重新整理了一替代方案
android·ios·小程序·https·uni-app·iphone·webview
2501_915918412 天前
中小团队发布,跨平台 iOS 上架,证书、描述文件创建管理,测试分发一体化方案
android·ios·小程序·https·uni-app·iphone·webview
家里有只小肥猫2 天前
uniApp打包ios报错
ios·uni-app
jingling5552 天前
uniapp | 基于高德地图实现位置选择功能(安卓端)
android·前端·javascript·uni-app