什么是跨域,如果本地开发遇到跨域怎么解决

跨域是浏览器的同源策略造成的,浏览器为了自身的安全功能,协议、域名、端口有一个不一致,就不允许跨域请求资源

1.前端跨域拿数据方法(具体实现自行搜搜)

https://segmentfault.com/a/1190000020686142?utm_source=tag-newest

(1)document.domain+iframe(主域相同,子域不同)

        强制设置document.domain为基础主域,实现了同域

(2)location.hash+iframe(通过中间页c来实现,利用iframe的location.hash传值)

   

(3)window.name+iframe(通过iframe的src属性从外域转向本域,跨域数据就从iframe的外域window.name转向本地域)

 

(4)window.postmessage

 2.跨域请求

(1)Jsonp(只能get请求)

 var script=doucument.createElement(‘script’)

   script.type=’text/javascript’

 script.src=”http://www.domain2.com:8080/login?userName=admin&callback=handleCallback”

 document.head.appendChild(script)

      //定义全局的回调函数

   function handleCallback(res){

       alert(JSON.stringify(res))

   }

 

(2)跨域资源共享CORS

         普通请求,前端不需要设置

         带cookie请求,xhr.withCredentials=true

(3)nginx代理跨域(起一个代理服务器)

(4)nodejs中间件代理跨域

         node+express+http-proxy-middleware搭建一个proxy服务器

         node+webpack+webpack-dev-server设置proxy参数

(5)webSocket协议跨域(HTML5的一种新的协议,实现了浏览器与服务器的全双工通信,socket.io)

 

3.本地开发跨域怎么解决

(1)webpack-dev-server中设置代理proxy的target和changeOrigoin

(2)express+http-proxy-middleware

posted on 2020-01-16 10:28  猪mother  阅读(2557)  评论(0编辑  收藏  举报