【问题标题】:How to access thingsboard REST API from browser javascript?如何从浏览器 javascript 访问thingboard REST API?
【发布时间】:2019-04-22 05:48:19
【问题描述】:

我是 thingsboard 的新手,我有一个 thingsboard 服务器。我正在尝试访问 thingsboard REST API 并以 CORS 错误告终,因为 OPTIONS 请求返回 401。

这是我的 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://localhost:8100”对“http://URL:PORT/api/customer/d8f7b410-5480-11e9-bc30-bd0cca1006d3/assets?limit=10”处的 XMLHttpRequest 的访问已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:没有“Access-Control-Allow-Origin”标头出现在请求的资源上。 请帮忙

【问题讨论】:

    标签: javascript thingsboard


    【解决方案1】:

    这是我的错。 xmlhttprequest 使用的 api 是 /api/customer/.. 等,但只为 /api/auth/**/api/v1/** 启用了 CORS 它不知何故错过了我的注意。

    我将 thingsboard.yml CORS 部分路径从 /api/v1/** 更改为 /api/**,现在错误没有发生。

    【讨论】:

      猜你喜欢
      • 2013-11-06
      • 1970-01-01
      • 2015-03-06
      • 1970-01-01
      • 2021-06-01
      • 1970-01-01
      • 2019-02-24
      • 1970-01-01
      • 2015-05-06
      相关资源
      最近更新 更多