Error 401 (Unauthorized) Access to API Using Javascript

Hi,

I’m trying to connect with the storage api using javascript & JQuery (Ajax) but it is not working.

I tested the api also in in Postman, Python and Curl and all tests were successful, hereby my javascript code:

var settings = {
    
    "url": "https://bartlett_workshop_environmental.data.thethingsnetwork.org/api/v2/devices",
    "method": "GET",
    "dataType":"jsonp",
    "headers": {
      "Accept": "application/json",
      "Authorization": "key ttn-accountv2 xxxxxxxxxxxxxxx  ",// (changed to account key)
    }
  }
  
  $.ajax(settings).done(function (response) {
    console.log(response);
  });

Result:
image

Could anyone help me out?

Thanks in Advance!

JSONP does not allow for setting headers, as that makes the browser generate a <script> tag, which don’t support that.

When not using JSONP, so for regular XHR/Ajax, browsers are far more secure than, e.g., some script or Postman. Specifically, by default an XHR request will not send the Authorization header when fetching data from a different domain. In your browser’s Network traffic you’ll see that it has been stripped out.

To fix that, you’d need to tell the browser to use withCredentials, which JQuery supports. However, that would require an OPTIONS request, and I don’t think TTN supports that. (It yields a 404 Not Found in my tests.)

See also Integrations - Data Storage / API generates a CORS error when accessed from script running in my browser.

1 Like

thanks for your reply!
Will have a look for on the added links

Hi @amaenhout, did you figure this out? I am trying to GET the data to my own website. I am not using JQuery and simply creating an instance of XMLHttpRequest() but I can not get it to work. My concern was that I wasn’t correctly formatting the Authorization Key before sending the request, as the same request made in Python seems to be working ok, but after finding this I am not so sure anymore.
Thanks!

This topic was automatically closed 60 days after the last reply. New replies are no longer allowed.