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);
12
  • depends upon how your server accepts token. mostly its accepts in Authorization Header. how you did it in postman? Commented Aug 7, 2019 at 5: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. Commented Aug 7, 2019 at 5: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. Commented Aug 7, 2019 at 5:54
  • are you getting some else errors like CORS..? Commented Aug 7, 2019 at 5: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 Commented Aug 7, 2019 at 5:58

2 Answers 2

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);
   }
});
Sign up to request clarification or add additional context in comments.

1 Comment

If do you get 401 Unauthorized Error. It is passing wrong token issue please verified you're token first.
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) {

            }
        });

1 Comment

Dinesh you should always leave a comment to your answer about why this solution works, posting only code, is not always helpful

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.