这个要注意,如果你请求后端时,请求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
}