Home > Back-end >  Ajax calling 401 unauthorized from backend in html
Ajax calling 401 unauthorized from backend in html

Time:12-03

I have a problem with my AJAX. Using Insomnia, I was able to get in with a successful response of 200 using the API token.

However, when I implement it in the HTML, I get a 401 response of access denied.

$.ajax({
  url: "https://ecoexchange.dscloud.me:8080/api/get",
  method: "GET",
  apikey: sessionStorage.getItem("apikey"),
  dataType: 'json',
  success: function(result) {
    $('#infoTable tr').empty();
    var header = $('#infoTable thead');
    var body = $('#infoTable tbody');
    var hTr;
    $('#infoTable thead').append(hTr = $('<tr>'));
    // Headers
    for (var h = 0; h < result.headers.length; h  ) {
      hTr.append($('<th>', {
        text: result.headers[h]
      }))
    }
    // Body
    for (var d in result.data) {
      var data = result.data[d];
      $('#infoTable tbody').append($('<tr>')
        .append($('<td>', {
          text: data.RecyclableID
        }))
        .append($('<td>', {
          text: data.Name
        }))
        .append($('<td>', {
          text: data.RecyclableType
        }))
      )
    }
  }
})
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

I am not sure how to put in the token or user name or password.

How can I improve the code so I don't get the error?

CodePudding user response:

What is this apikey parameter you're using? That's not in the documentation.

apikey: sessionStorage.getItem("apikey"),

Did you mean to pass it as a header instead? For example:

headers: {"apikey": sessionStorage.getItem("apikey")},

The documentation for the service you're using should specify how to include the API key. Presumably you have that information, because:

Using Insomnia, I was able to get in with a successful response

So you'll need to include the value in your AJAX request wherever it belongs. Most likely as either a header value or a query string value. But the jQuery .ajax() function isn't going to know how to pass the value, you have to specify.

CodePudding user response:

I think your problem is with passing parameters which can be solved here

Or you can read the jQuery.get() docs here

  • Related