0

When I make my get request with POSTMAN, it works just fine and I get the expected response. I just set type to GET, insert my URL and insert a key named token and set it to a token I get from another service. but when I try to call the same service in code like this:

$.ajax({
    type: 'get',
    headers: {"token": myToken},
    url: myURL,
    success: function (data) {
        console.log(data);
    }
});

or this:

$.ajax({
    type: 'GET',
    beforeSend: function(xhr, setting){xhr.setRequestHeader('token', myToken);},
    url: myURL,
    success: function (data) {
        console.log(data);
    }
});

I get 401 error. I also found out that the server is not receiving the token in the request header. Any ideas how I can fix this? Cheers.

=====================================================

UPDATE: POSTMAN generated code which fails as well:

var settings = {
  "async": true,
  "crossDomain": true,
  "url": "https://test.mirasnafis.ir/marketer/rating",
  "method": "GET",
  "headers": {
    "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1bmlxdWVfbmFtZSI6IjEwY2U5NTUxLWExNTItNDc2ZC05ZTA0LTIyOGMyOGUwMmEwYSIsIm5iZiI6MTU2NTE1NDU0NywiZXhwIjoxNTk2Nzc2OTQ3LCJpYXQiOjE1NjUxNTQ1NDcsImlzcyI6Imh0dHA6Ly9sb2NhbGhvc3Q6NTAxOTEiLCJhdWQiOiJodHRwOi8vbG9jYWxob3N0OjUwMTkxIn0.YhdwgSW1NzHavdtXTMlHOvbOmgjlUXk81PKGg4v0cXc",
    "User-Agent": "PostmanRuntime/7.15.2",
    "Accept": "*/*",
    "Cache-Control": "no-cache",
    "Postman-Token": "c7e92763-dc2e-4db8-a442-c5b8275e7bf5,d6fa9ad9-29e2-482e-9c46-de89f9a42c3b",
    "Host": "test.mirasnafis.ir",
    "Accept-Encoding": "gzip, deflate",
    "Connection": "keep-alive",
    "cache-control": "no-cache"
  }
}

$.ajax(settings).done(function (response) {
  console.log(response);
});

and

var data = null;

var xhr = new XMLHttpRequest();
xhr.withCredentials = true;

xhr.addEventListener("readystatechange", function () {
  if (this.readyState === 4) {
    console.log(this.responseText);
  }
});

xhr.open("GET", "https://test.mirasnafis.ir/marketer/rating");
xhr.setRequestHeader("token", "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1bmlxdWVfbmFtZSI6IjEwY2U5NTUxLWExNTItNDc2ZC05ZTA0LTIyOGMyOGUwMmEwYSIsIm5iZiI6MTU2NTE1NDU0NywiZXhwIjoxNTk2Nzc2OTQ3LCJpYXQiOjE1NjUxNTQ1NDcsImlzcyI6Imh0dHA6Ly9sb2NhbGhvc3Q6NTAxOTEiLCJhdWQiOiJodHRwOi8vbG9jYWxob3N0OjUwMTkxIn0.YhdwgSW1NzHavdtXTMlHOvbOmgjlUXk81PKGg4v0cXc");
xhr.setRequestHeader("User-Agent", "PostmanRuntime/7.15.2");
xhr.setRequestHeader("Accept", "*/*");
xhr.setRequestHeader("Cache-Control", "no-cache");
xhr.setRequestHeader("Postman-Token", "c7e92763-dc2e-4db8-a442-c5b8275e7bf5,8da9d6a1-0670-41f5-8049-3b96a28b0e3f");
xhr.setRequestHeader("Host", "test.mirasnafis.ir");
xhr.setRequestHeader("Accept-Encoding", "gzip, deflate");
xhr.setRequestHeader("Connection", "keep-alive");
xhr.setRequestHeader("cache-control", "no-cache");

xhr.send(data);
Eclipse-
  • 51
  • 3
  • 11
  • depends upon how your server accepts token. mostly its accepts in Authorization Header. how you did it in postman? – Ravi Aug 07 '19 at 05:50
  • Can you please show how you have set this in postman? Also, can you try making the request using curl or wget? That will help you to figure out why it is not working in your AJAX call. – fiveelements Aug 07 '19 at 05:52
  • @RV in the 3rd tab which is titled Headers, set a `KEY` to token and its VALUE to the string I get from another service. – Eclipse- Aug 07 '19 at 05:54
  • are you getting some else errors like CORS..? – Ravi Aug 07 '19 at 05:55
  • @ArashChM maybe it can help, but postman can generate code for you with a working get or post call. So after you ran the code, You can find a button to the right called `code` (just below your send button) and here you can select `javascript` from the dropdown – Carsten Løvbo Andersen Aug 07 '19 at 05:58
  • @RV yes im getting that error after the 401 – Eclipse- Aug 07 '19 at 06:01
  • https://stackoverflow.com/questions/36568923/cors-error-with-ajax-request. or https://stackoverflow.com/questions/35553500/xmlhttprequest-cannot-load-xxx-no-access-control-allow-origin-header this might help you. – Ravi Aug 07 '19 at 06:05
  • @CarstenLøvboAndersen I didn't know that feature existed. however i ran both XHR and jquery codes provided by postman, first I got 4 new errors saying `refused to add unsafe header` for user agent and 3 others. I also got the former errors as well. After removing them, I still get the errors I started with. I will update the post with postman code. – Eclipse- Aug 07 '19 at 06:07
  • Check this : https://stackoverflow.com/questions/3258645/pass-request-headers-in-a-jquery-ajax-get-call – Alpesh Jikadra Aug 07 '19 at 06:14
  • @RV the jsonp solution removed the CORS error but I still get the 401 – Eclipse- Aug 07 '19 at 06:34
  • didnt get mean by jsonp!! – Ravi Aug 07 '19 at 06:50
  • try passing header like this. beforeSend: function (xhr) { xhr.setRequestHeader ("Authorization", "Custom " + btoa("token:" + yourToken)); }, – Ravi Aug 07 '19 at 06:56

2 Answers2

2

Please check this is work!!!

Always token accepted in JSON format so need to pass in 'Accept': 'application/json' OR 'Contact-type': 'application/json'.

 $.ajax({
   type: "GET",
   headers: {
      'token': Token,
      'Accept': 'application/json',
   },
   url: YOURURL,
   cache: false,
   success: function(result) {
       console.log(result);
   }
});
0
$.ajax({
            url: URL,
            type: 'GET',
            dataType: 'json',
            headers: {
                'header1': 'value1',
                'header2': 'value2'
            },
            contentType: 'application/json; charset=utf-8',
            success: function (result) {
               // CallBack(result);
            },
            error: function (error) {

            }
        });
Dinesh K
  • 269
  • 2
  • 8