HTTPS请求在Node.js中不起作用(代码400)

时间:2018-07-12 09:36:22

标签: node.js rest api http-post httprequest

我是Node.js的新手,并尝试使用基本auth和标头/正文调用现有的API。 Here是有关我尝试使用的API的更多详细信息。我总是收到400码作为答复。请检查我所附的代码段:

// Include the request library for Node.js   
var request = require('request');
//  Basic Authentication credentials   
var username = 'myEmail';
var password = 'mySuperSecret';
var authenticationHeader = "Basic " + new Buffer(username + ":" + password).toString("base64");

var json = '{"device":"","os_type":"Android","os_version":"4.0","dvc_manuf":"unknown","dvc_type":"unknown"}';
var jsonstring = JSON.stringify(json);

const options = {
    method: 'POST',
    uri: 'https://api.indego.iot.bosch-si.com/api/v1/authenticate',
    headers: {
        'Authorization': 'Basic ' + new Buffer(username + ':' + password).toString('base64'),
        'Content-Type': 'application/json',
        'Content-Length': jsonstring.length
    },
    body : jsonstring
  }

  request(options, function(err, res, body) {  

  if (!err && res.statusCode == 200) {
    let jsonbody = JSON.parse(body);
    console.log(jsonbody);
    console.log(res);
    console.log(res.statusCode);
  }
});

我还尝试了一个Web客户端来测试API,并成功:https://client.restlet.com/ enter image description here

任何建议我做错了什么? 谢谢, tro

2 个答案:

答案 0 :(得分:0)

我建议您进行更改,

在您的options变量中,url的下一行应更改为uri

uri: 'https://api.indego.iot.bosch-si.com/api/v1/authenticate',

也仅在呼叫成功时将响应放置在显示器上

  if (!error && response.statusCode == 200) {
    let jsonbody = JSON.parse(body);
    console.log(jsonbody);
    console.log(res);
    console.log(res.statusCode);
  }

希望这会有所帮助!

答案 1 :(得分:0)

我尝试了以下方法,现在可以了:

var request = require('request-promise');


var options = {
  method: 'POST',
  uri: 'https://api.indego.iot.bosch-si.com/api/v1/authenticate',
  
  headers: {
    'Authorization': 'Basic myBasicAuth',
    'Content-Type': 'application/json',
    'Content-Length': '116'
  },
  
  body: {
      "device":"",
      "os_type":"Android",
      "os_version":"4.0",
      "dvc_manuf":"unknown",
      "dvc_type":"unknown"
  },
  json: true // Automatically stringifies the body to JSON
};



request(options, function (err, response, body) {
  var reason;
  if (err) {
      reason = {
          cause: err,
          error: err,
          options: options,
          response: response
      };
} else if (!(/^2/.test('' + response.statusCode))) { // Status Codes other than 2xx
      reason = {
          statusCode: response.statusCode,
          error: body,
          options: options,
          response: response
      };
  }
});