I am new to thingsboard and I have a thingsboard server. I am trying to access the thingsboard REST API and ending up with CORS errors because the OPTIONS request is returning 401.
This is my thingsboard.yml and by default it seems CORS is supported with '*'
spring.mvc.cors:
mappings:
# Intercept path
"/api/auth/**":
#Comma-separated list of origins to allow. '*' allows all origins. When not set,CORS support is disabled.
allowed-origins: "*"
#Comma-separated list of methods to allow. '*' allows all methods.
allowed-methods: "POST,GET,OPTIONS"
#Comma-separated list of headers to allow in a request. '*' allows all headers.
allowed-headers: "*"
#How long, in seconds, the response from a pre-flight request can be cached by clients.
max-age: "1800"
#Set whether credentials are supported. When not set, credentials are not supported.
allow-credentials: "true"
I checked this question Thingsboard No 'Access-Control-Allow-Origin' header is present on the requested resource. angularjs but I am not clear how to disable authentication for OPTIONS as commented. I tried the code in link but getting 401.
var url = "http://THINGSBOARDURL:PORT/api/customer/d8f7b410-5480-11e9-bc30-bd0cca1006d3/assets?limit=10";
var xhr = createCORSRequest('GET', url);
if (!xhr) {
alert('CORS not supported');
return;
}
// Response handlers.
xhr.onload = function() {
var text = xhr.responseText;
console.log(text);
};
xhr.onerror = function() {
alert('Woops, there was an error making the request.');
};
xhr.setRequestHeader("Accept", "application/json")
xhr.setRequestHeader("X-Authorization","Bearer JWTTOKEN")
xhr.send();
Access to XMLHttpRequest at 'http://URL:PORT/api/customer/d8f7b410-5480-11e9-bc30-bd0cca1006d3/assets?limit=10' from origin 'http://localhost:8100' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Please help
It was my mistake. The api used by xmlhttprequest was /api/customer/..
etc but CORS was enabled for only /api/auth/**
and /api/v1/**
It somehow missed my notice.
I changed thingsboard.yml CORS section path from /api/v1/**
to /api/**
and now the error does not occur.