具有授权的Ajax请求

时间:2014-11-30 23:27:01

标签: jquery ajax bad-request

我尝试使用autorization标头创建ajax请求:

enter image description here

但得到:GET http://agroagro.com/agroMobile/v1/tasks 400 (Bad Request)

我的ajax代码:

$(function() { 

if (localStorage.getItem('apiKey') == '') {
window.location.replace("login.html");  
}
    else {  

var urlAjax = "http://agroagro.com/agroMobile/v1/tasks";

$.ajax({
type:'GET',
url: urlAjax,
contentType: "application/x-www-form-urlencoded",
headers: {
    "Authorization": localStorage.getItem('apiKey')
  },
beforeSend: function(jqXHR) {
    console.log(localStorage.getItem('apiKey'));
    jqXHR.setRequestHeader("Authorization", localStorage.getItem('apiKey'));
},

  success: function(data) { 

    console.log('Lets do something');  


  },
error: function(data) {
    //window.location.replace("login.html");
    console.log(data); 
    console.log(console.log(localStorage.getItem('apiKey')));
  $('#error').append('<p>Please enter the correct information</p>');
    },
dataType: 'json',

});

    }

});

为什么我会收到此错误?正如你所看到的,我发送了正确的autorization api密钥,一切都很好,但只是不工作......

1 个答案:

答案 0 :(得分:1)

通过手动访问URL,我可以看到您缺少API密钥。您应该能够在控制台的预览/响应选项卡中查看请求的内容。这可能会给你很多信息。

您是否阅读了所连接服务的API文档?