1. 概述
1.1 说明
在vue项目中,存在直接前端访问某一服务/硬件等情况,一般使用axios/fetch的get方法去访问(服务端允许跨域访问)获取拿到对应信息;但在访问硬件(如身份证读取器)时,本地服务访问与项目服务跨域时,接口访问还是存在跨域问题,此时使用JSONP访问来解决跨域问题;
2.1 JSONP代码
jsonpAPI(url) {
// eslint-disable-next-line
return new Promise((resolve, reject) => {
window.jsonCallBack = (result) => {
resolve(result)
}
const JSONP = document.createElement('script')
JSONP.type = 'text/javascript'
JSONP.src = url
document.getElementsByTagName('head')[0].appendChild(JSONP)
setTimeout(() => {
document.getElementsByTagName('head')[0].removeChild(JSONP)
}, 500)
})
},
2.2 VUE调用
const res = await this.jsonpAPI('http://localhost:8989/api/ReadMsg')
2.3 代码功能
封装jsonp访问方法:jsonpAPI
vue调用jsonp访问:this.jsonpAPI