步骤:

由于直接访问百度在线api会跨域,配置代理解决跨域:
vue.config.js中配置

devServer: {
    port: port,
    open: true,
    overlay: {
      warnings: false,
      errors: true
    },
    proxy: {
      '/baiduOCR': {
        target: 'https://aip.baidubce.com', // 百度在线请求地址https://aip.baidubce.com/oauth/2.0/token
        changeOrigin: true,
        secure: false, // 因为是https 地址需要次选项
        pathRewrite: {
          '^/baiduOCR': ''
        }
      }
    }
  },
  //注意:配置完一定要重启项目!!!

封装获取access_token请求:

// OCR识别
export function identificationRecognize(params) {
  return request({
    url: '/baiduApi/oauth/2.0/token',
    method: 'get',
    params
  })
}

组件中直接引用调用:

import { identificationRecognize } from '@/api/user/driver'

created() {
    const data = { //这三个参数不能少
      grant_type: 'client_credentials',//固定参数
      client_id: 'Bf69EFs5C0iImsEGB4SAlpnF',//你申请的AK
      client_secret: '3hWvIKI4lhgUOqziHCIosUDtPBixMmE9'//你申请的SK
    }
    identificationRecognize(data).then(res => { console.log(`access_token---`, res) })
  }

打印结果:
在这里插入图片描述

Logo

前往低代码交流专区

更多推荐