1

在HTML标签里,一些标签比如script、img这样的获取资源的标签是没有跨域限制的,利用这一点,我们可以这样干。
简单版前端:

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8">
  5. </head>
  6. <body>
  7. <script type='text/javascript'>
  8. // 后端返回直接执行的方法,相当于执行这个方法,由于后端把返回的数据放在方法的参数里,所以这里能拿到res。
  9.      window.jsonpCb = function (res) {
  10.        console.log(res)
  11. }
  12. </script>
  13. <script src='http://localhost:9871/api/jsonp?msg=helloJsonp&cb=jsonpCb' type='text/javascript'></script>
  14. </body>
  15. </html>

2.空iframe加form

细心的朋友可能发现,JSONP只能发GET请求,因为本质上script加载资源就是GET,那么如果要发POST请求怎么办呢?

  1. {
  2. // 首先创建一个用来发送数据的iframe.
  3. const iframe = document.createElement('iframe')
  4.  iframe.name = 'iframePost'
  5.  iframe.style.display = 'none'
  6.  document.body.appendChild(iframe)
  7. const form = document.createElement('form')
  8. const node = document.createElement('input')
  9. // 注册iframe的load事件处理程序,如果你需要在响应返回时执行一些操作的话.
  10.  iframe.addEventListener('load', function () {
  11.    console.log('post success')
  12. })
  13.  form.action = url
  14. // 在指定的iframe中执行form
  15.  form.target = iframe.name
  16.  form.method = 'post'
  17. for (let name in data) {
  18.    node.name = name
  19.    node.value = data[name].toString()
  20.    form.appendChild(node.cloneNode())
  21. }
  22. // 表单元素需要添加到主文档中.
  23.  form.style.display = 'none'
  24.  document.body.appendChild(form)
  25.  form.submit()
  26. // 表单提交后,就可以删除这个表单,不影响下次的数据发送.
  27.  document.body.removeChild(form)
  28. }
  29. // 使用方式
  30. requestPost({
  31.  url: 'http://localhost:9871/api/iframePost',
  32.  data: {
  33.    msg: 'helloIframePost'
  34. }
  35. })

3.CORS
CORS是一个W3C标准,全称是"跨域资源共享"(Cross-origin resource sharing)跨域资源共享 CORS 详解。看名字就知道这是处理跨域问题的标准做法

4.代理
Nginx配置:

  1. server{
  2. # 监听9099端口
  3. listen 9099;
  4. # 域名是localhost
  5.    server_name localhost;
  6. #凡是localhost:9099/api这个样子的,都转发到真正的服务端地址http://localhost:9871
  7. location ^~ /api {
  8.        proxy_pass http://localhost:9871;
  9. }
  10. }
同源策略限制下Dom查询的正确打开方式

1.postMessage

window.postMessage() 是HTML5的一个接口,专注实现不同窗口不同页面的跨域通讯


catalina
61 声望2 粉丝