跨域
文章目录
在HTML标签里,一些标签比如script、img这样的获取资源的标签是没有跨域限制的,利用这一点,我们可以这样干。
简单版前端:
<!DOCTYPE html><html><head><meta charset="utf-8"></head><body><script type='text/javascript'>// 后端返回直接执行的方法,相当于执行这个方法,由于后端把返回的数据放在方法的参数里,所以这里能拿到res。window.jsonpCb = function (res) {console.log(res)}</script><script src='http://localhost:9871/api/jsonp?msg=helloJsonp&cb=jsonpCb' type='text/javascript'></script></body></html>
2.空iframe加form
细心的朋友可能发现,JSONP只能发GET请求,因为本质上script加载资源就是GET,那么如果要发POST请求怎么办呢?
{// 首先创建一个用来发送数据的iframe.const iframe = document.createElement('iframe')iframe.name = 'iframePost'iframe.style.display = 'none'document.body.appendChild(iframe)const form = document.createElement('form')const node = document.createElement('input')// 注册iframe的load事件处理程序,如果你需要在响应返回时执行一些操作的话.iframe.addEventListener('load', function () {console.log('post success')})form.action = url// 在指定的iframe中执行formform.target = iframe.nameform.method = 'post'for (let name in data) {node.name = namenode.value = data[name].toString()form.appendChild(node.cloneNode())}// 表单元素需要添加到主文档中.form.style.display = 'none'document.body.appendChild(form)form.submit()// 表单提交后,就可以删除这个表单,不影响下次的数据发送.document.body.removeChild(form)}// 使用方式requestPost({url: 'http://localhost:9871/api/iframePost',data: {msg: 'helloIframePost'}})
3.CORS
CORS是一个W3C标准,全称是"跨域资源共享"(Cross-origin resource sharing)跨域资源共享 CORS 详解。看名字就知道这是处理跨域问题的标准做法
4.代理
Nginx配置:
server{# 监听9099端口listen 9099;# 域名是localhostserver_name localhost;#凡是localhost:9099/api这个样子的,都转发到真正的服务端地址http://localhost:9871location ^~ /api {proxy_pass http://localhost:9871;}}
同源策略限制下Dom查询的正确打开方式
1.postMessage
window.postMessage() 是HTML5的一个接口,专注实现不同窗口不同页面的跨域通讯

评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论