一、概述
uniapp中的webview组件可以使用本地网页和网络网页。
使用本地网页的过程中,发送请求,会出现跨域问题,并且通过抓包会发现origin
请求头的值为"null"
。
请求示例代码
// 创建xhr对象 var xhr = new xmlhttprequest(); // 创建一个 put 请求,采用异步 xhr.open('put', 'http://192.168.1.47:8086/load_balance/test', true); // 注册相关事件 xhr.onload = (event) => { console.log("event=====", event) }; xhr.onerror = (error) => { console.log("error=========", error) }; // 发送请求 xhr.send();
二、解决方案
上述示例代码中,如果后端不做跨域处理,请求则无法正常访问,到底为什么会出现跨域问题呢,而且origin
请求头的值为什么这么奇怪。
其实我们可以通过查看浏览器地址栏信息得到答案,通过打印window.location.href
的值,我们可以看到如下结果
查看地址栏的值
console.log("window.location.href====", window.location.href); // window.location.href==== file:///var/mobile/containers/data/application/7084a02a-514f-4b7b-a966-f610315939c1/documents/pandora/apps/b01189ffe7e81940832ddc748b2ede9e/www/hybrid/html/index.html
我们可以发现,本地网页是通过file://协议进行访问的,并不是http协议,所以当我们发送http请求时,这个请求并不符合同源策略。
由于file协议中没有域名和端口之类的信息,所以origin
请求头的值会为"null"
。
知道原因之后,我们其实可以通过让后端设置允许"null"跨域即可,不过这样做会感觉奇奇怪怪的。
还有一种方式,可以直接在前端解决掉这个问题,不需要用到后端。
就是使用5+api中的plus.net.xmlhttprequest
对象,这个请求对象就是专门用来解决跨域问题的。
所以,让我们来修改上述示例代码。
请求示例代码(不会触发跨域)
// 记得要在plusready事件完成之后才能调用plus对象 document.addeventlistener('plusready', () =>{ // 使用plus.net.xmlhttprequest创建xhr对象 var xhr = new plus.net.xmlhttprequest(); // 创建一个 put 请求,采用异步 xhr.open('put', 'http://192.168.1.47:8086/load_balance/test', true); // 注册相关事件 xhr.onload = (event) => { console.log("event=====", event) }; xhr.onerror = (error) => { console.log("error=========", error) }; // 发送请求 xhr.send(); })
用了plus.net.xmlhttprequest
对象之后,便不会出现跨域问题了。
总结
到此这篇关于uniapp webview页面中的请求跨域问题解决的文章就介绍到这了,更多相关uniapp webview页面请求跨域内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论