美文网首页
vue项目解决axios jsonp请求

vue项目解决axios jsonp请求

作者: 三亿 | 来源:发表于2019-12-20 17:15 被阅读0次

    众所周知,jsonp一般是解决前端跨域的渠道之一,先从浅入深讲解过渡的历史。

    ajax模式请求下的jsonp跨域

    $(document).ready(function(){
        $.ajax({
            url:'http://xxxxx:8080/set_session_jsonp',
            type:'get', 
            async:true,   
            timeout:5000,  
            dataType:'jsonp',    //返回的数据格式:json/xml/html/script/jsonp/text 
            success:function(data,textStatus,jqXHR){
                console.log(data);
            },
            error:function(xhr,textStatus){
                console.log("请求失败"); 
            }
        })    
    });
    

    输出结果:{errcode: 0, errmsg: "成功"},输出的内容是我们想要的。√

    axios模式请求下的jsonp跨域

        axios.get('http://xxxxx:8080/set_session_jsonp').then(function (response) {
            console.log(response);
        }).catch(function (error) {
            console.log(error);
        });
    

    然后我们发现,undefined({"errcode":0,"errmsg":"成功"});多了undefined,这显然不是我们期望看到的。
    同事提起jsonp是附带另外一个callback的函数,这个时候我们把callback带上,看看返回的结果。

        axios.get('http://xxxxx:8080/set_session_jsonp?callback').then(function (response) {
            console.log(response);
        }).catch(function (error) {
            console.log(error);
        });
    

    输出:({"errcode":0,"errmsg":"成功"});,好像有点接近了,自己转换下其实也还是可以的。但这明显跟ajax模式下的jsonp跨域结果不一致。
    我们继续查找axios文档说明,发现作者是建议采用cors解决跨域问题,这样会更方便前端点。
    所以我们只能封装下再调用。

    axios.jsonp = (url) => {
        if(!url){
            console.error('请传入一个url参数')
            return;
        }
        return new Promise((resolve,reject) => {
            window.jsonCallBack =(result) => {
                resolve(result)
            }
            var JSONP=document.createElement("script");
            JSONP.type="text/javascript";
            JSONP.src=`${url}&callback=jsonCallBack`;
            document.getElementsByTagName("head")[0].appendChild(JSONP);
            setTimeout(() => {
                document.getElementsByTagName("head")[0].removeChild(JSONP)
            },500)
        })
    } 
    
    axios.jsonp('http://xxxxx:8080/set_session_jsonp?callback=demo').then(function (response) {  
        console.log(response);
        }).catch(function (error) {
        console.log(error);
        });
    
    //demo = 页面上其他方法的函数名 
    
    

    得到结果:{errcode: 0, errmsg: "成功"},输出的内容也正是我们想要的。√


    但现在都是vue框架模式下开发,直接挂载jsonp方法总感觉不佳,我们看下有没有更加模块化引用的方式更加方便点,所以...

    vue项目解决axios jsonp请求

    通过npm安装jsonp jsonp文档

    npm install jsonp --save   
    
    const jsonp = require('jsonp');
    
    jsonp('http://xxxxx:8080/set_session_jsonp', null, (err, data) => {
      if (err) {
        console.error(err.message);
      } else {
        console.log(data);
      }
    });
    
    

    最终:{errcode: 0, errmsg: "成功"}

    相关文章

      网友评论

          本文标题:vue项目解决axios jsonp请求

          本文链接:https://www.haomeiwen.com/subject/ydeinctx.html