最近对微信小程序比较感兴趣,想写一个查询车辆违章记录的小程序。在调用外部接口时需要,appcode 这种authoriztion。发现微信小程序的
ajax请求使用这种方式不起作用。改为直接在header中赋值生效了,不知道什么原因,希望遇到同样问题的伙伴可以不用弯路。
beforeSend: function (xhr){ console.log('授权码'); xhr.setRequestHeader("Authorization", "APPCODE "+"XXXXXXXXXXXXXXXXXXX"); },
解决方法
header: { 'content-type': 'application/json', 'Authorization': "APPCODE " + "XXXXXXXXXXXXXXXXXXX" },
详细代码如下
confirm: function () { console.log("clicked confirm"); this.setData({ hidden: true }); var timestamp = new Date().getTime(); var apiUrl = "http://ddycapi.market.alicloudapi.com/violation/query";
//注释掉的代码为废弃车首页和路帮网的免费接口,使用阿里云的api收费服务 //var appId = "129"; //var appKey = "4263c4f0-4f56-0135-3375-0242c0a80006"; //var carInfo = "{plate_num=" + this.data.plateNo + "&body_num=" + this.data.frameNo + "&engine_num=" + this.data.engineNo + "&city_id=190&car_type=02}"; // var signStr = appId + carInfo + timestamp + appKey; // var sign = util.md5(signStr); //console.log("carInfo:" + carInfo); //console.log("signStr:" + signStr); //console.log("sign:" + sign); //var url = apiUrl + "car_info=" + carInfo + "&api_id=" + appId + "&sign=" + sign + "×tamp=" + timestamp; // console.log("url:" + url);
var that = this; wx.request({ url: apiUrl, method:'post', data: { "plateNumber": "陕AD3738", "engineNo": "695176712", "vin": "662722", "carType": "02" }, header: { 'content-type': 'application/json', 'Authorization': "APPCODE " + "XXXXXXXXXXXXXXXXXXX" }, beforeSend: function (xhr){ console.log('授权码'); xhr.setRequestHeader("Authorization", "APPCODE "+"XXXXXXXXXXXXXXXXXXX"); }, success: function (res) { if (res.statusCode != 200) { console.log('接口调用异常'); that.setData({ resultModalHidden: false, resultMsg: '接口调用异常' }); } var obj = res.data; var status = Number(obj.status); that.setData({ resultModalHidden: false }); switch (status) { case 1002: console.log('app_id有误'); break; case 1003: console.log(' sign加密有误'); break; case 1004: console.log('车牌号,汽车类型,违章城市 等字段不能为空'); break; case 1005: that.setData({ resultMsg: '输入的车辆信息有误,请查证后重新输入' }); console.log('车辆信息有误'); break; case 2000: that.setData({ resultMsg: '恭喜,当前城市交管局暂无您的违章记录' }); console.log('正常(无违章记录)'); break; case 2001: console.log('正常(有违章记录)'); break; case 5000: console.log('请求超时,请稍后重试'); break; case 5001: console.log('交管局系统连线忙碌中,请稍后再试'); break; case 5002: console.log('恭喜,当前城市交管局暂无您的违章记录'); break; case 5003: console.log('数据异常,请重新查询'); break; case 5004: console.log('系统错误,请稍后重试'); break; case 5005: console.log(' 车辆查询数量超过限制'); break; case 5006: console.log('你访问的速度过快, 请后再试'); break; case 5008: that.setData({ resultMsg: '输入的车辆信息有误,请查证后重新输入' }); console.log('输入的车辆信息有误,请查证后重新输入'); break; default: console.log('未知错误'); } console.log(res) } }) },