H5网络请求适配We码指南
在We码中需要使用HWH5.fetchInternet请求,为省去开发将项目中的请求改成We码请求API代码的环节,平台提供了此请求适配的补丁文件。
适用场景:使用浏览器XMLHttpRequest或fetch对象的请求(如axios请求在浏览器端使用XHR),支持服务端返回json和text的格式。
限制说明:此API不支持文件相关请求格式,如需要,可移步至平台文件相关JSAPI。
1、下载补丁文件,将它在 html 文件中全局引入,以及在hwh5.js之后再引入:
<script src="../../../../common/js/hwh5.js"></script>
<!-- 引入示例:在JSAPI脚本之后引入,相对路径根据项目需要调整 -->
<script src="../hwh5.compatible.js"></script>
2、页面中可直接使用axios请求(在浏览器端,axios是基于XMLHttpRequest请求)或window.fetch请求,如:
axios
const jsonUrl = 'https://open-doc.welink.huaweicloud.com/docs/component/reactui/dist/plugin.json';
const textUrl = 'https://open-doc.welink.huaweicloud.com';
axios({
url: jsonUrl
}).then((reply)=> {
console.log('axios#json:', reply);
}).catch((error)=> {
console.log('axios#error', error);
});
axios({
url: textUrl
}).then((reply)=> {
console.log('axios#text:', reply);
}).catch((error)=> {
console.log('axios#error', error);
});
window.fetch
const jsonUrl = 'https://open-doc.welink.huaweicloud.com/docs/component/reactui/dist/plugin.json';
const textUrl = 'https://open-doc.welink.huaweicloud.com';
window.fetch(jsonUrl, {
method: 'GET'
}).then((res)=> {
return res.json();
}).then((data)=>{
console.log('window.fetch#response json data', data);
}).catch((error)=>{
console.log('window.fetch#error', error);
});
window.fetch(textUrl, {
method: 'GET'
}).then((res)=> {
return res.text();
}).then((data)=>{
console.log('window.fetch#response text data', data);
}).catch((error)=>{
console.log('window.fetch#error', error);
});
3、引入此补丁后,将拦截请求,走We码的HWH5.fetchInternet请求。如需改动,可在请求前去调用 HWH5.setRequestIntercept 进行切换:
HWH5.setRequestIntercept({
name: 'fetchVPN' // 默认:fetchInternet,有效值为fetchInternet或fetchVPN
});