- Download jsonp npm install jsonp
- Add one to the js folder to encapsulate a jsonp()
How to encapsulate a jsonp()
In the downloaded jsopn, jsonp(url, options, callback) is a parameter in the native jsonp method;
Introduce downloaded jsonp
import originJsonp from 'jsonp';
Export your own defined jsonp function
//This jsonp function is defined by us and is not the same as the originJsonp above. OriginJsonp is a method that can be directly referenced; she is the most
Finally return a Promise object
export default function jsonp(url, data, option){ return new Promise((resolve,reject)=>{ //Call originJsonp() to grab the data originJsonp(url,option,(err,data)=>{ //Callback is the result of the data being crawled if(!err){ resolve(data) }ese{ reject(err) } }) }) }
Parameters are often passed in the crawled URL, but these parameters are in the object format. However, the parameters we pass into the originJsonp method are spliced after the url, so they cannot be the object format. At this time, you need to splice the parameters of the object format to the url to form a new URL.
A url similar to this: (/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 determine whether data is empty //Split the data together if(vaule){ urlData += ·'&'${k}=${encodeURIComponent(value)}·;//encodeURIComponent will splice the URL (encodeURIComponent() is to convert the string into the URL address } } return urlData ? (1):''; //The reason (1) is that it is possible that the parameters followed by this url are used '? ‘;We just need to connect the parameters with ‘&’, regardless of the symbol immediately after the URL [What? still&】}
Reference function param to function jsonp
export default function jsonp(url, data, option) { return new Promise((resolve,reject)=>{ //Calling cross-domain request function //Split the URL. The home page needs to determine whether there is "?" after the URL. If so, add "&" to param(data), otherwise you need to add "param(data)?" url = ('?')<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 succeeds }else{ reject(err) //fail } }) }) }
Summarize
The above is the method of using jsonp to grab cross-domain data in the Vue project introduced by the editor. I hope it will be helpful to everyone!