I am new with Node.js and try to call an existing API with basic auth and header/body. Here are more details about the API I try to use. I always receive a 400 code as response. Please check my attached code snippet:
// 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); } });
I also tried a web client to test the API and was successful: https://client.restlet.com/
Any suggestions what I did wrong? Thanks, tro
Couple of changes I would suggest you to make,
In your options
variable the below line the url
should be change to uri
as,
uri: 'https://api.indego.iot.bosch-si.com/api/v1/authenticate',
Also place the display the response only when the call gets succeeds,
if (!error && response.statusCode == 200) {
let jsonbody = JSON.parse(body);
console.log(jsonbody);
console.log(res);
console.log(res.statusCode);
}
Hope this helps!
I tried the following and now it works:
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 }; } });
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.