javascript NodeJS POST请求返回错误的JSON错误,但它是吗?

ffvjumwh  于 5个月前  发布在  Java
关注(0)|答案(1)|浏览(70)

我尝试为恒温器调用Google NEST API,但出现以下错误:

{
    "error": {
      "code": 400,
      "message": "Invalid JSON payload received. Unknown name \"params[heatCelsius]\": Cannot bind query parameter. Field 'params[heatCelsius]' could not be found in request message.",
      "status": "INVALID_ARGUMENT",
      "details": [
        {
          "@type": "type.googleapis.com/google.rpc.BadRequest",
          "fieldViolations": [
            {
              "description": "Invalid JSON payload received. Unknown name \"params[heatCelsius]\": Cannot bind query parameter. Field 'params[heatCelsius]' could not be found in request message."
            }
          ]
        }
      ]
    }
  }

字符串
以下是我如何创建post数据:

var temp = req.query.temp;
    var coolOrHeat = req.query.coolHeat;

    let celsius = (temp - 32) * 5 / 9;

    var jsonDataObj;

    if (coolOrHeat == "heat") {
        jsonDataObj = {
            command: 'sdm.devices.commands.ThermostatTemperatureSetpoint.SetHeat',
            params: {
                heatCelsius: celsius
            }
        }
    }

    if (coolOrHeat == "cool") {
        jsonDataObj = {
            command: 'sdm.devices.commands.ThermostatTemperatureSetpoint.SetCool',
            params: {
                coolCelsius: celsius
            }
        }
    }


以下是我的POST请求:

var urlSetTemp = 'https://smartdevicemanagement.googleapis.com/v1/enterprises/' + projectId + '/devices/' + thermId + ':executeCommand';

            request.post({
                headers: {
                    'content-type': 'application/json',
                    'Authorization': 'Bearer ' + accessToken
                },
                form: jsonDataObj,
                url: urlSetTemp
            }, function (error, response, body) {

                var json = JSON.parse(body);
                console.log("res: ", json);

                res.json({
                    'json': json,
                    'ack': "success",
                    'body': jsonDataObj
                });
            });


谷歌文档:https://developers.google.com/nest/device-access/traits/device/thermostat-temperature-setpoint#setheat
最后,在Postman中,它很好,它可以工作,但在Node中不行。
我到底做错了什么?


的数据

fwzugrvs

fwzugrvs1#

现在我已经可以使用了,我设置了body而不是form,并且使用了JSON.stringify,并将JSON设置为true。

request.post({
                headers: {
                    'content-type': 'application/json',
                    'Authorization': 'Bearer ' + accessToken
                },
                body: JSON.stringify(jsonDataObj),
                json: true,
                url: urlSetTemp
            }, function (error, response, body) {

                var json = JSON.parse(body);
                console.log("res: ", json);

                res.json({
                    'json': json,
                    'ack': "success",
                    'body': jsonDataObj
                });
            });

字符串

相关问题