vue3.x使用fetch-jsonp请求jsonp接口
dearweb
发布:2021-08-09 11:18:31阅读:
在vue我们用的最多的就是axios请求接口数据,而axios又不支持jsonp请求,所以我们需要利用fetch-jsonp去请求jsonp的接口,下面我们一起来看看fetch-jsonp的使用方法吧。
fetch-jsonp安装
使用npm 安装 npm install fetch-jsonp
fetch-jsonp的使用
注意:IE8/9/10/11 不支持 ES6 Promise,在你的应用程序开始时运行它来填充全局环境。
require('es6-promise').polyfill();在vue代码块中的用法
<template>
<div class></div>
</template>
<script>
// 引入依赖
import fetchJsonp from 'fetch-jsonp'
export default {
name: "",
created() {
// 发起请求
this.fetchJsonp();
},
methods: {
// 以简单的方式来获取 JSONP
fetchJsonp() {
fetchJsonp("请求地址...")
.then(function(response) {
return response.json();
})
.then(function(json) {
console.log("parsed json", json);
})
.catch(function(ex) {
console.log("parsing failed", ex);
});
},
// 设置 JSONP 回调参数名称,默认为 'callback'
fetchJsonpCallback() {
fetchJsonp("请求地址...", {
jsonpCallback: "custom_callback"
})
.then(function(response) {
return response.json();
})
.then(function(json) {
console.log("parsed json", json);
})
.catch(function(ex) {
console.log("parsing failed", ex);
});
},
// 设置 JSONP 回调函数名称,默认为带有 json_ 前缀的随机数
fetchJsonp_json_() {
fetchJsonp("请求地址...", {
jsonpCallbackFunction: "function_name_of_jsonp_response"
})
.then(function(response) {
return response.json();
})
.then(function(json) {
console.log("parsed json", json);
})
.catch(function(ex) {
console.log("parsing failed", ex);
});
},
// 设置 JSONP 请求超时,默认为 5000ms
fetchJsonp_5000() {
fetchJsonp("/users.jsonp", {
timeout: 5000
})
.then(function(response) {
return response.json();
})
.then(function(json) {
console.log("parsed json", json);
})
.catch(function(ex) {
console.log("parsing failed", ex);
});
}
}
};
</script>
<style lang='less' scoped>
</style>上述代码主要给大家讲了一下以基本的方式来获取 JSONP,设置 JSONP 回调参数名称,默认为 'callback',设置 JSONP 回调函数名称,默认为带有 json_ 前缀的随机数, 设置 JSONP 请求超时,默认为 5000ms等几个用法,一切还要结合实际项目来使用,希望本文档对你有帮助。
小礼物走一波,支持作者
赏还没有人赞赏,支持一波吧