Using jsonp to grab cross domain data in Vue project

  • Download jsonp NPM install jsonp
  • Add a jsonp.js in the JS folder to encapsulate a jsonp()

How to encapsulate a jsonp()

In the downloaded jsopn, JSON (url, options, callback) is a parameter in the native JSON method;

  1. Introducing download jsonp

      import originJsonp from 'jsonp';
  2. Export your own defined JSON functions

    //This JSON function is defined by ourselves. It is not the same as originJsonp above. originJsonp is a method that can be directly referenced. Finally, it returns a Promise object
    
      export default function jsonp(url, data, option){
       return new Promise((resolve,reject)=>{
       //Call originJsonp() to grab data
         originJsonp(url,option,(err,data)=>{ //callback is the result of fetching data
            if(!err){
            resolve(data)
            }ese{
            reject(err)
            }
         })
    
       })
    } 
    
  3. In the captured data URL, parameters are often passed in, but these parameters are in the object format. However, the parameters we pass in the originJsonp method are spliced behind the URL, so they cannot be in the object format. In this case, the parameters in the object format need to be spliced behind the URL to form a new URL
    A url like this:( https://www.baidu.com/s?ie=ut...
    Here parameter data:{

                 ie:utf-8,
                 rsv_bp:1
               }
    
    export function param(data){
    
    let urlData='';
    
    for(let key in data){
      let value = data[k] !== undefined ? data[k] : '' ;//Used to judge whether data is empty
      //Splicing data
      if(vaule){
      urlData += ·'&'${k}=${encodeURIComponent(value)}·;//Encodeuriccomponent splices URLs (encodeuriccomponent() converts strings to URLs
      }
    }
     return urlData ? urlData.substring(1):''; //The reason for url.substring(1) is that it is possible that the parameter followed by this URL uses'? We only need to connect the parameters with '&', regardless of the symbol [yes? Or /]
    }
    
    
  4. Reference function param to function JSON

     export default function jsonp(url, data, option) {
    
       return new Promise((resolve,reject)=>{
         //Call cross domain request function
         //For URL splicing, the home page needs to determine whether there is a "?" "&" should be added to param(data), otherwise "?" should be added to param(data)
         url = url.indexOf('?')<0 ? '?':'&' + param(data);
         originJsonp(url,option,(err,data)=>{
           //The url here is the complete request address, which needs to include parameters
           if(!err){
             resolve(data)  //Request successful
           }else{
             reject(err)  //fail
           }
         })
       })
     }
    
    
    
    

Keywords: Javascript JSON IE npm

Added by hypertech on Sat, 09 Nov 2019 16:22:37 +0200