0

In Charles proxy I've captured a successful request made when using curl - which returns some json. I've tried all day to make this into an ajax call but have failed - wonder if someone could take a fresh look at it? I'm sending a token via the header to a service that provides this json

{
"category": [{
    "id": 1,
    "name": "aaa",
    "description": "anything..."
}, {
    "id": 2,
    "name": "ccc",
    "description": "desc 1111..."
}, {
    "id": 3,
    "name": "ddd",
    "description": "desc..."
}]
}

charles dump of the good request made with curl

    GET /api/v1/category HTTP/1.1
    User-Agent  curl/7.30.0
    Host    myurl.com
    Accept  */*
    Authorization   Token token=6ff1fed470ec2ddaf8b3af9584619902

the raw info

    URL http://myurl.com/api/v1/category
    Status  Complete
    Response Code   200 OK 
    Protocol    HTTP/1.1
    Method  GET
    Kept Alive  No
    Content-Type    application/json; charset=utf-8
    Client Address  /127.0.0.1
    Remote Address  myurl.com/23.23.121.64

my attempt

$.ajax({
beforeSend: function (xhr) { xhr.setRequestHeader ('Authorization', 'Token 6ff1fed470ec2ddaf8b3af9584619902') },
type: "GET",
url: "http://myurl.com/api/v1/category",
dataType: "json"
}).done(function( msg ) {
console.log( msg );

}).fail(function(jqXHR, textStatus, errorThrown) {
console.log( "Request failed: " + textStatus );
console.log( errorThrown );
});

thanks in advance!

MikeW
  • 4,749
  • 9
  • 42
  • 83

1 Answers1

0

You haven’t posted the diagnostics for your attempt, so I’m just going to guess from your code.

  1. You send

    Authorization: Token 6ff1fed470ec2ddaf8b3af9584619902

    from XHR, but

    Authorization: Token token=6ff1fed470ec2ddaf8b3af9584619902

    from curl—note the token=.

  2. You have to make sure that http://myurl.com/api/v1/category either supports cross-origin resource sharing or is located at the same origin (domain) as the page that executes that JavaScript code.

If these do not help, post whatever error messages you get.

Vasiliy Faronov
  • 11,840
  • 2
  • 38
  • 49
  • Thanks for your reply. My attempt is to set a separate api to the client, so will look at what's needed for CORS support. So far I am returning the result in JSONP. What's interesting is in Charles Proxy, if I edit a failed request and paste in a new line "Authorization: Token token=1234 etc .. then it works. Nothing I can do will make that stick in setRequestHeader though. – MikeW Mar 01 '14 at 09:48
  • @MikeW If you want JSONP, your `$.ajax` call is incorrect, check the docs. Otherwise please post diagnostics for your failing case. – Vasiliy Faronov Mar 01 '14 at 13:19