请求跨域的解决方法JSONP的使用

因为同源策略的问题,让我在前端开发的时候经常会遇到跨域问题。
啥是同源策略?
就说在遇到主机协议端口号不相同的时候那就会跨域。
为啥要有同源策略?
同源策略是一个重要的安全策略,它用于限制一个origin的文档或者它加载的脚本如何能与另一个源的资源进行交互。它能帮助阻隔恶意文档,减少可能被攻击的媒介。
解决问题的方法
一、JSONP
JSONP的原理就是动态的创建script标签。因为script不被同源策略约束着。那就可以用这个去解决跨域问题
原生实现方法

	let scripts = document.createElement('script');
    scripts.type = 'text/javascript';
    scripts.src = `https://api.apiopen.top/getJoke?page=1&count=2&type=video&callback=demo`;
    document.querySelector('body').appendChild(scripts);
	function demo(res){
    
    
        console.log(res)
    }

在没有使用jsonp的时候,会正常返回数据 例如{msg: ‘helloworld’};
使用了jsonp以后
具体方法需要在我们请求的地址后面携带一个callback的参数。
服务端在接受到请求 然后用这个参数值包装要返回的数据:demo({msg: ‘helloworld’});
我们还可以看到demo这个函数,这个就是用来接收服务端返回的信息。
我自己把这个方法封装了一下。

		let url = 'https://api.apiopen.top/getJoke?page=1&count=2&type=video';
        let demo;
        function addscript(url){
    
    
            return new Promise((resolve,reject) =>{
    
    
                let urls ;
                if(url.indexOf('?') > -1){
    
    
                  urls  = url+'&callback=demo';
                }else{
    
    
                  urls = url+'?callback=demo';
                }
                let scripts = document.createElement('script');
                scripts.type = 'text/javascript';
                scripts.src = urls;
                document.querySelector('body').appendChild(scripts);
                demo = (res) =>{
    
    
                    resolve(res);
                }
            })
        }
        //使用方法
        addscript(url).then(res =>{
    
    
            console.log(res)
        });

jquery是可以直接使用的JSONP。

		let url = 'https://api.apiopen.top/getSingleJoke?sid=28654780';
        $.ajax({
    
    
            url:url,
            type:'get',
            dataType: 'jsonp',  // 请求方式为jsonp
            jsonpCallback: 'demo', // 自定义回调函数名
            data:{
    
    }
        })
        function demo(res){
    
    
            console.log(res)
        }

后续接着更新。。。
参考文档:
https://segmentfault.com/a/1190000017312269
https://developer.mozilla.org/zh-CN/docs/Web/Security/Same-origin_policy

猜你喜欢

转载自blog.csdn.net/weixin_44655037/article/details/115124840