如何从浏览器JavaScript访问Thingsboard REST API?

时间:2019-04-22 05:48:20

标签: javascript thingsboard

我是物联网的新手,并且有物联网服务器。由于OPTIONS请求返回401,因此我试图访问Thingsboard REST API并最终出现CORS错误。

这是我的Thingsboard.yml,默认情况下,似乎'*'支持CORS

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"

我检查了这个问题Thingsboard No 'Access-Control-Allow-Origin' header is present on the requested resource. angularjs,但不清楚如何禁用已评论的OPTIONS的身份验证。我尝试了链接中的代码,但得到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();

从原点“ http://URL:PORT/api/customer/d8f7b410-5480-11e9-bc30-bd0cca1006d3/assets?limit=10”到“ http://localhost:8100”处对XMLHttpRequest的访问已被CORS策略阻止:对预检请求的响应未通过访问控制检查:否'Access-Control-Allow-来源的标头出现在请求的资源上。 请帮助

1 个答案:

答案 0 :(得分:1)

这是我的错误。 xmlhttprequest使用的api是/api/customer/..等,但是仅对/api/auth/**/api/v1/**启用了CORS 它以某种方式错过了我的注意。

我将Thingsboard.yml CORS节的路径从/api/v1/**更改为/api/**,现在不会发生错误。