0
点赞
收藏
分享

微信扫一扫

前端解决跨域的方法

minute_5 2022-01-12 阅读 83
前端

https://segmentfault.com/a/1190000011145364

一、jsonp跨域

jsonp缺点:只能实现get一种请求。

1. 原生实现

<script>
   var script = document.createElement('script');
   script.type = 'text/javascript';
   // 传参一个回调函数名给后端,方便后端返回时执行这个在前端定义的回调函数
    script.src = 'http://www.domain2.com:8080/login?user=admin&callback=handleCallback';
    document.head.appendChild(script);
    // 回调执行函数
    function handleCallback(res) {
        console.log(JSON.stringify(res))
        //删除script标签
    }
</script>
// 服务端返回:(返回时即执行全局函数)
handleCallback({"status": true, "user": "admin"})

2. jquery ajax

$.ajax({
    url: 'http://www.domain2.com:8080/login',
    type: 'get',
    dataType: 'jsonp',  // 请求方式为jsonp
    jsonpCallback: "handleCallback",    // 自定义回调函数名
    data: {}
});

3. vue.js

this.$http.jsonp('http://www.domain2.com:8080/login', {
    params: {},
    jsonp: 'handleCallback'
}).then((res) => {
    console.log(res); 
})

二、跨域资源共享(CORS)

普通跨域请求:只服务端设置Access-Control-Allow-Origin即可,前端无须设置,若要带cookie请求:前后端都需要设置。

1. 原生实现

在这里插入图片描述

2. jQuery ajax

$.ajax({
    ...
   xhrFields: {
       withCredentials: true    // 前端设置是否带cookie
   },
   crossDomain: true,   // 会让请求头中包含跨域的额外信
});息,但不会含cookie

3. vue框架

  1. axios设置
axios.defaults.withCredentials = true
  1. vue-resource设置:
Vue.http.options.credentials = true

三、 nginx反向代理跨域

通过nginx配置一个代理服务器(域名与domain1相同,端口不同)做跳板机,反向代理访问domain2接口,并且可以顺便修改cookie中domain信息,方便当前域cookie写入,实现跨域登录。(后端)
前端只需要访问代理的服务器即可

var xhr = new XMLHttpRequest();

// 前端开关:浏览器是否读写cookie
xhr.withCredentials = true;

// 访问nginx中的代理服务器
xhr.open('get', 'http://www.domain1.com:81/?user=admin', true);
xhr.send();

四、 document.domain + iframe跨域

实现原理:两个页面都通过js强制设置document.domain为基础主域,就实现了同域。 (主域相同,子域不同的跨域应用场景)
在这里插入图片描述
包含前后端代码:
https://segmentfault.com/a/1190000011145364

举报

相关推荐

0 条评论