0

The following request works fine:

curl -X GET --header 'Accept: application/json' --header 'X-Authorization: Bearer eyNI6GJ0DA9ObwNA1QAv3oqN2zWWQHsiAxR3m-QZjtaw' 'http://host:port/api/tenant/devices?limit=10'

Now I need to perform the same request through jquery.ajax().

I have tried this:

var mytoken = "Bearer eyNI6GJ0DA9ObwNA1QAv3oqN2zWWQHsiAxR3m-QZjtaw ";

$.ajax({
    type: 'GET',        
    url: "http://" + host + ":" + port + "/api/tenant/devices?limit=10",      
    contentType: "application/json",
    dataType: "JSON",       
    xhrFields: {
        withCredentials: true
    },    
    beforeSend: function(xhr) {
        console.log("beforesend");
        xhr.setRequestHeader ("X-Authorization", mytoken);
    },    
    success:function(data) {
        console.log(data);
    },
    error:function(error){
        console.log(error);
    }
});

What I obtained is:

Response: {"status":401,"message":"Authentication failed","errorCode":10,"timestamp":1518184124772}

Console:

Failed to load http://host:port/api/tenant/devices?limit=10: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. The response had HTTP status code 401.

Which is the right way to traslate the working curl rest to jquery ajax?

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
user1052004
  • 93
  • 2
  • 6
  • cURL is not governed by the Same Origin Policy as Javascript is. If you control the domain you're calling, you can add the required CORS headers to the response. If you do not control that domain then you will not be able to call it directly through JS code. – Rory McCrossan Feb 09 '18 at 14:06
  • Thanks @Rory, your link is very usefull. – user1052004 Feb 09 '18 at 14:36
  • You didn't pass header in AJAX call. Without header with JWT token thingsboard.io will not accept your API call. Use the Bearer Token – Jigs Virani Jul 17 '18 at 07:53

0 Answers0