对于vue中的jsonp请求,借助第三方的jsonp
对应的文档 https://www.npmjs.com/package/jsonp
1.安装jsonp
cnpm install jsonp --save-dev
2.直接在项目中引入,并封装jsonp请求的函数
import jsonp from "jsonp"
/*封装promise的jsonp请求*/
export default function getJsonp(url,data,option){
url+=(url.indexOf("?") < 0 ? "?" : "&") + params(data)
return new Promise(function(resolve,reject){
jsonp(url,option,(err,data)=>{
if(!err){
resolve(data)
}else{
reject(err)
}
})
})
}
/*处理参数*/
function params(data){
let url='';
for(let k in data){
let val = data[k]!==undefined?data[k]:'';
url+=`&${k}=${encodeURIComponent(val)}`
}
return url?url.substring(1):''
}
3.对于jsonp有三个参数,官方文档这样介绍的
jsonp(url, opts, fn)
url (String) url to fetch
opts (Object), optional
param (String) name of the query string parameter to specify the callback (defaults to callback)
//param默认的回调名称为callback ==>{param:'callback'},此参数为对象,踩过坑,谨记
timeout (Number) how long after a timeout error is emitted. 0 to disable (defaults to 60000)
//timeout默认的超时时间为60000毫秒 ===>{timeout:60000}
prefix (String) prefix for the global callback functions that handle jsonp responses (defaults to __jp)
//prefix前缀,默认的前缀为__jp ==>{prefix:__jp}
name (String) name of the global callback functions that handle jsonp responses (defaults to prefix + incremented counter)
//name指的就是前缀名拼接上一个自增的数字,如__jp0
fn callback
//fn 回调函数