前端常用的几种解决跨域问题的方法。

什么是跨域?

跨域是指一个域下的文档或脚本试图去请求另一个域下的资源,是由浏览器同源策略限制的一类请求场景。

什么是同源策略?

所谓同源是指:域名、协议、端口都要相同。

解决跨域方法

通过jsonp跨域

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) {
        alert(JSON.stringify(res));
    }
 </script>

2. jquery ajax:

        $.ajax({
            url: "URL",
            dataType: 'jsonp', // 请求方式为jsonp
            success: function(jsonp) {
                console.log('ok');
            },
            error: function() {
                console.log('no');
            }
        });

  

3. vue.js:

this.$http.jsonp('http://www.domain2.com:8080/login', {
    params: {},
    jsonp: 'handleCallback'
}).then((res) => {
    console.log(res); 
})
posted @ 2021-01-30 10:40  wuami  阅读(209)  评论(0)    收藏  举报