JSONP跨域请求在Vue中怎么用?一直报错
我在Vue项目里想用JSONP请求第三方接口,但总是失败,浏览器控制台提示“Uncaught ReferenceError: callback is not defined”。我试过动态创建script标签,也试过axios-jsonp插件,都不行。
下面是我现在写的代码,接口是百度搜索的suggest接口,应该支持JSONP:
<template>
<div>{{ result }}</div>
</template>
<script>
export default {
data() {
return { result: '' }
},
mounted() {
const script = document.createElement('script')
script.src = 'https://suggestion.baidu.com/su?wd=前端&cb=callback'
document.head.appendChild(script)
},
methods: {
callback(res) {
this.result = res.s[0]
}
}
}
</script>
这个callback方法根本没被调用,是不是作用域问题?该怎么正确绑定回调函数?
两个解决方案:
1. 简单粗暴的直接挂window上:
2. 更优雅的用jsonp库(推荐):
先安装
jsonp这个包第二种方式更靠谱,不用手动处理script标签和全局污染。JSONP这种上古技术现在确实用得少了,CORS才是王道,但遇到必须用JSONP的老接口也没办法。