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