Web Star
Web Star

Reputation: 432

Simple API call with "Bearer" token Authorization using Ajax

My problem is that I couldn't fetch data from API using Ajax.

I'm using a JWT token for authentication and when I call the API from Postman, I get the data successfully.

enter image description here

However, when calling the API using ajax, an ERR_ABORTED 401 (Unauthorized) error is detected. Here's the code:

$.ajax({
    type: "GET",
    url: API_URL,
    dataType: 'jsonp',
    contentType: "application/json",
    headers: {
        "Cache-Control": "no-cache",
        "Authorization": "Bearer " + access_token,
    },
    data: {}, 
    success: function(resp){
        console.log(resp)
    }, 
    error: function(error){
    }    
})

Also, I get the same error when I copy and use the code snippet generated by POSTMAN.

enter image description here

I've searched a lot of answers for this and applied them, but it doesn't work for me.

Can someone help with this?

Thank you in advance.

Upvotes: 0

Views: 2485

Answers (1)

nicholas koskey
nicholas koskey

Reputation: 9

You have an error on line 5... it should be dataType: 'json'.

The solution:

$.ajax({
    type: "GET",
    url: API_URL,
    dataType: 'json',
    contentType: "application/json",
    headers: {
        "Cache-Control": "no-cache",
        "Authorization": "Bearer " + access_token,
    },
    data: {}, 
    success: function(resp){
        console.log(resp)
    }, 
    error: function(error){
    }    
});

Upvotes: 0

Related Questions