javascript - 七牛fetch接口抓取第三方資源(網絡圖片),Js寫ajax請求返回error錯誤信息總是“Unauthorized”
問題描述
fetch請求授權失敗了不知道是path拼接錯誤還是寫的ajax請求有錯誤。
//管理憑證function genManageToken(accessKey, secretKey, pathAndQuery, body) {
var str = pathAndQuery + 'n' + body;var hash = CryptoJS.HmacSHA1(str, secretKey);var encodedSign = CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse(hash));return accessKey + ':' + encodedSign;
}
var fetchImg = function(picUrl) {
// 通過fetch進行遠程圖片抓取var accessKey = 'AK';var secretKey = 'SK';//網絡圖片picurl上傳到七牛var srcUrl = CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse(picUrl));var bucket = CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse('bucket'));var path = '/fetch/' + srcUrl + '/to/' + bucket;var fetchUrl = 'http://iovip.qbox.me/' + path;mui.ajax(fetchUrl, { dataType: ’json’, //服務器返回json格式數據 type: ’post’, //HTTP請求類型 timeout: 10000, //超時時間設置為10秒; headers: {’Authorization’: 'QBox ' + genManageToken(accessKey, secretKey, path, ''),’Content-Type’: ’application/json’, }, success: function(data) {//服務器返回響應,根據響應結果,分析是否登錄成功;data = JSON.stringify(data);data = eval('(' + data + ')');//輸出響應成功key值console.log(data[’key’]); }, error: function(xhr, type, errorThrown) {//異常處理;console.log(errorThrown); }});
}
問題解答
回答1:function safe64(base64) {
base64 = base64.replace(/+/g, '-');base64 = base64.replace(///g, '_');return base64;
}function genManageToken(accessKey, secretKey, pathAndQuery, body) {
var str = pathAndQuery + 'n' + body;var hash = CryptoJS.HmacSHA1(str, secretKey); var encodedSign = safe64(hash.toString(CryptoJS.enc.Base64));
}編碼問題已解決。
