真-vue使用jsonp跨域
vue使用jsonp跨域
1.安装依赖
npm install jsonp
2.在vue文件中使用
import originJSONP from 'jsonp' //后端接口返回的数据为字符串 //ckp({"cityid":"101190201","date":"2020-11-14"}}) //该字符串实际是把数据用ckp()函数包裹 //ckp就是前后端约定的jsonP前缀 let url4 = 'https://www.xxxapi.com/api?callback=ckp'; let opts={ prefix:'ckp' } //发起jsonP请求 originJSONP(url4, opts, (err, data) => { console.log('????????????????===') if (!err) { console.log(data); this.weatherJson = data; } else { console.log(err) } });
3.originJSONP函数介绍
originJSONP(url, opts, fn),有3个参数 1.fn 回调方法,用es6 Promise 2.url (String) 服务器端数据接口地址 3.opts (Object) 一般只需关注param即可 3.1 param (String) 默认是callback,这是与后端约定的参数名称,也可以随便定义,只要前后端统一 3.2 timeout (Number) 请求超时时间,默认是6000ms 3.3 prefix (String) callback值的前缀,默认是__jp 3.4 name (String) 指定全局注册的回调方法名,一般不会用到,因为默认是prefix+自增数字