关于vue 使用百度ocr识别跨域问题
关于vue 使用百度ocr识别行驶证
1.登录地址
获取access_token
由于vue的axios请求百度ocr识别接口 会出现跨域问题 可以使用代理解决(vue 2.0 和 vue3.0 解决如下)
1.vue 2.0 proxyTable 代理解决:在config目录下的index.js文件中添加如下配置即可
// An highlighted block
module.exports = {
dev: {
// Paths
assetsSubDirectory: 'static',
assetsPublicPath: './',
proxyTable: {
'/baiduApi': {
target: 'https://aip.baidubce.com', //访问地址
changeOrigin: true,
secure: false, //只有代理https 地址需要次选项
pathRewrite: {
'^/baiduApi': ''
}
}
},
- vue 3.0 proxy代理解决:在vue.config.js文件中的devServer中添加如下配置即可
// An highlighted block
proxy: {
'/baiduApi': {
target: 'https://aip.baidubce.com', //访问地址
changeOrigin: true,
secure: false, //只有代理https 地址需要次选项
pathRewrite: {
'^/baiduApi': ''
}
}
},
这个只能本地 线上用nginx代理
location ~ ^/(baiduApi)/.* {
rewrite ^.+baiduApi/?(.*)$ /$1 break;
include uwsgi_params;
root /usr/share/nginx/html;
proxy_pass https://aip.baidubce.com;
}
- 经过配置代理后即可请求获取access_token的接口
this.axios.get('/baiduApi/oauth/2.0/token?grant_type=client_credentials&client_id=iBlglRY8dh8HyKXBwgOkyn6H&client_secret=32uqmGIdHqjCK1xk7L7U2D7RcrBRkVRG&',{headers:{
dataType:'json'
}}).then(res =>{
if(res.status ==200){
this.access_token = res.data.access_token;
}
})
在 el-upload的 on-change事件中写入转化base64
1.promise封装 将图片转base64
//将图片转为base64格式
transformBase64(file){
return new Promise(((resolve, reject) => {
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function(e){
resolve(e.target.result)
}
}))
},
2.promise封装 请求百度OCR行驶证识别
链接: 百度OCR行驶证识别接口文档.
carIdentify(ocrImg){
return new Promise(((resolve, reject) => {
var params = new FormData();
params.append('image',ocrImg);
params.append('detect_direction', true );
params.append('vehicle_license_side', 'front' );
params.append("access_token", this.access_token);
axios.post("/baiduApi/rest/2.0/ocr/v1/vehicle_license?access_token",params,
{headers: {'content-type': 'application/x-www-form-urlencoded'} }
).then((res)=>{
resolve(res.data.words_result)
})
}))
},
3.在 el-upload 的 on-change事件中 请求上面两个 promise请求
uploadImg(file,fileList){
this.transformBase64(file.raw).then(data=>{
this.carIdentify(data).then(res=>{
console.log(res)
})
})
},