簡體   English   中英

HTTPS請求在Node.js中不起作用(代碼400)

[英]HTTPS request is not working in Node.js (Code 400)

我是Node.js的新手,並嘗試使用基本身份驗證和標頭/正文調用現有的API。 以下是有關我嘗試使用的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/ 在此處輸入圖片說明

有什么建議我做錯了嗎? 謝謝,tro

我建議您進行一些更改,

在您的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);
  }

希望這可以幫助!

我嘗試了以下方法,現在可以使用:

 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 }; } }); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM