对 Netatmo 的节点 HTTP POST 请求

Node HTTP POST Request to Netatmo

我正在尝试使用 NodeJS 向我的 Netatmo 气象站的云发出 http POST 请求。它确实需要是 http post 而不是使用节点的 'request' 模块,因为我打算在 AWS Lambda 中使用它,而该模块目前在那里不受支持。

无论我尝试什么,我都会得到可怕的 {"error":"invalid_request"},结果为 400.. 我不知道问题出在哪里。

这是我的片段:

var querystring = require('querystring');
var https = require('https');  
function getNetatmoData(callback, cardTitle){
        var sessionAttributes = {};

        var shouldEndSession = false;
        cardTitle = "Welcome";
        var speechOutput =""; 
        var repromptText ="";

        console.log("sending request to netatmo...")

        var payload = querystring.stringify({
            'grant_type'    : 'password',
            'client_id'     : clientId,
            'client_secret' : clientSecret,
            'username'      : userId,
            'password'      : pass,
            'scope'         : 'read_station'
      });

        var options = {
            host: 'api.netatmo.net',
            path: '/oauth2/token',
            method: 'POST',
            'Content-Type': 'application/x-www-form-urlencoded',
           'Content-Length': Buffer.byteLength(payload)

        };

        //console.log('making request with data: ',options);

        var req = https.request(options, function(res) {
                res.setEncoding('utf8');

                 console.log("statusCode: ", res.statusCode);
                 console.log("headers: ", res.headers);

                res.on('data', function (chunk) {
                    console.log("body: " + chunk);

                });

                res.on('error', function (chunk) {
                    console.log('Error: '+chunk);
                });

                res.on('end', function() {

                    speechOutput = "Request successfuly processed."
                    console.log(speechOutput);
                    repromptText = ""
                    //callback(sessionAttributes, buildSpeechletResponse(cardTitle, speechOutput, repromptText, shouldEndSession));
                });

            });

            req.on('error', function(e){console.log('error: '+e)});
            req.write(payload);

            req.end();
    }

这是 Cloud9 的控制台日志:

Debugger listening on port 15454
sending request to netatmo...
statusCode:  400
headers:  { server: 'nginx',
  date: 'Tue, 24 Nov 2015 19:30:25 GMT',
  'content-type': 'application/json',
  'content-length': '27',
  connection: 'close',
  'cache-control': 'no-store',
  'access-control-allow-origin': '*' }
body: {"error":"invalid_request"}
Request successfuly processed.

Aarrgh..我监督了一些事情。显然, headers 需要在发出请求时在选项中设置。在 headers 变量中设置了 Content-Type 和 Content-Length。

事不宜迟,这里是选项变量的正确工作方式:

var options = {
    host: 'api.netatmo.net',
    path: '/oauth2/token',
    method: 'POST',
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Content-Length': Buffer.byteLength(payload)
    }

};