2

我似乎无法通过 Nest API 获取我的访问令牌。我尝试以 3 种不同的方式发布到访问令牌 URL,但它们都给出了相同的结果。

我正在使用以下代码:

<body>
  <button type = 'button' id = 'connect' class = 'btn btn-default'>Connect To Nest</button>
  <div id = 'pinArea'>
      <label for = 'pin'>Enter PIN Here: </label><input type = 'text' name = 'pin' id = 'pin'><br />
      <button type = 'button' class = 'btn btn-default' id = 'pinSubmit'>Submit</button>
  </div>


  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
  <script src="js/bootstrap.min.js"></script>
  <script type = 'text/javascript'>
      $(document).ready(function() {

          function makeid()
            {
                var text = "";
                var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

                for( var i=0; i < 5; i++ )
                    text += possible.charAt(Math.floor(Math.random() * possible.length));

                return text;
            }

          $("#connect").click(function() {
              var state = makeid();
              window.open('https://home.nest.com/login/oauth2?client_id=MYCLIENTID&state='+state+'');
              $("#connect").hide();
              $("#pinArea").show();
          });

          $("#pinSubmit").click(function() {
              var pin = $("#pin").val();
              $.ajax({
                  url: "https://api.home.nest.com/oauth2/access_token?code="+pin+"&client_id=MYCLIENTID&client_secret=MYCIENTSECRET&grant_type=authorization_code",
                  //data: {code: pin, client_id: "MYCLIENTID", client_secret: "MMYCLIENTSECRET", grant_type: "authorization_code"},
                  type: "POST",
                  success: function(res) {
                      console.log(res);
                  },
                  error: function(e) {
                      console.log(e);
                  }
              });
          });
      });
  </script>

问题是 URL 在我的控制台中给出了以下错误,当它应该发回我的访问令牌时:

XMLHttpRequest cannot load https://api.home.nest.com/oauth2/access_token. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://fatslug.ca' is therefore not allowed access. 

关于可能导致这种情况的任何想法?我只是做错了吗?!

4

2 回答 2

4

问题是 Nest 在其令牌交换步骤中不支持 COR。我认为这是故意的,但我真的不确定。

相反,Nest 似乎更喜欢您构建一个服务器并通过该服务器代理令牌交换。做起来很简单。

但是,如果您真的想在浏览器中进行令牌交换(并且不要对生产中的任何事情执行此操作或认真对待隐私/安全),那么您可以使用类似 cors-anywhere.com 的服务:

"https://cors-anywhere.herokuapp.com/api.home.nest.com/oauth2/access_token?" +
"code="+auth.authorizationCode+"&" +
"client_id="+clientId+"&" +
"client_secret="+clientSecret+"&" +
"grant_type=authorization_code"

这会将请求发送到 cors-anywhere,这将为请求提供 COR 支持并代理到 Nest。

于 2014-06-25T15:04:46.847 回答
0

我不认为它与 CORS 有任何关系,就像 Nest 需要 POST 一样。

于 2015-04-18T22:46:39.797 回答