我有api_key,秘密,我必须将签名哈希到sha256。签名= api_key + secret + utctimestamp。我正在使用Crypto.Js进行散列。我收到了以下错误
XMLHttpRequest cannot load "HOST LINK". No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin localhost is therefore not allowed access
以下是我的代码
var app = (function($){
var baseURL = 'http://xyz.herokuapp.com/api/v1';
var apiSecretKey = 'ABC';
var apiKey = '123';
var init = function(){
$('#login').on('click', function(e){
e.preventDefault();
login();
});
};
var login = function() {
var u = encodeURIComponent($('#username').val());
var p = encodeURIComponent($('#password').val());
$.ajax({
type: "POST",
url: baseURL + "/login",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify({email: u, password: p}),
beforeSend: function (request) {
request.setRequestHeader('Access-Control-Allow-Origin', 'http://localhost');
request.setRequestHeader('X-HASH', getHMAC(apiKey, timestamp));
},
success: function (data) {
$('.loggedIn').show();
console.log(data);
$('.loggedIn .name').text("Hello ");
},
error: function (errorMessage) {
alert('Error logging in');
}
});
};
timestamp = new Date().getTime() / 1000;;
var getHMAC = function(key, timestamp) {
var hash = CryptoJS.SHA256(key+timestamp+apiSecretKey);
return hash.toString();
};
return {
init:init
};
})(jQuery);
app.init();
错误是由于错误的散列还是CORS问题引起的。这是我第一次使用HMAC身份验证,我不知道我这样做是对还是错。
Google开发者工具会向我提供此信息![在此处输入图片说明] [1]
REQUEST Method: OPTION
Status Code: 200 Ok
Request Header
Access-Control-Request-Headers:access-control-allow-origin, accept, content-type, x-hash
Access-Control-Request-Method:POST
Response Header
Allow:DELETE, POST, OPTIONS
Connection:keep-alive
Content-Length:0
Content-Type:text/html; charset=utf-8
Date:Mon, 04 Aug 2014 21:30:06 GMT
Server:gunicorn/18.0
Via:1.1 vegur