let options = {
'method': 'GET',
'url': `https://cdn-api.co-vin.in/api/v2/appointment/sessions/public/calendarByPin?pincode=${row.pincode}&date=${day}`,
'headers': {
}
};
request(options, function (error, re) {
if (error) {
console.log('error in request',error)
}
else if(re) {
let data = JSON.parse(re.body);
console.log(data)
}
})
It's working fine in localhost, but when I'm hosting it on digital ocean server, sometime the code executes sometimes it doesn't, it happens with the same code. Please help
You are getting html code instead of json in your api response. Add this to headers
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
}
also try checking the html that you got, it can possibly provide you with a clue why you are getting it
Related
so I am trying to send a http request to a server and as response I should get the body where all the information I need is in. When I then try to .parseJSON() the body I get an exception telling me that my body is empty. There is no way that the body is really empty so there has to be a mistake in the code.
I can not give you the whole code because of passwords and stuff like that.
Code:
public addVehicle(): Promise<void>{
return new Promise<void>((resolve, reject) => {
const options = {
url: [URL],
method: "POST",
headers: {
'Content-Type': 'application/json',
'Authorization': [user/psw],
'token': [authToken]
},
body: JSON.stringify({
'vehicleID': vehicleID,
'externalID': externalID,
'brandID': vehicleBrandId,
'modelGroupID': vehicleModelId,
'typeName': typeName,
'segmentationID': vehicleSegmentationId,
'categoryID': vehicleCategoryId,
'fuelTypeID': vehicleFuelTypeId,
'transmissionTypeID': vehicleTransmissionTypeId,
'propulsionTypeID': vehiclePropulsionTypeId,
'registerationDate': registerationDate,
'powerKW': powerKW,
'description': description
})
}
let req = request.post(options, (err, res, body) => {
let rawAuth = JSON.parse(body);
console.log(body);
resolve();
})
})
}
Try removing the JSON.stringify().
I am assuming that your receiving API expects the fields in the body. Sending the data as string will hide the fields from the receiving API. It will just see one string object (not sure what the key will be tho).
const options = {
url: [URL],
method: "POST",
headers: {
'Content-Type': 'application/json',
'Authorization': [user/psw],
'token': [authToken]
},
body: {
'vehicleID': vehicleID,
'externalID': externalID,
'brandID': vehicleBrandId,
'modelGroupID': vehicleModelId,
'typeName': typeName,
'segmentationID': vehicleSegmentationId,
'categoryID': vehicleCategoryId,
'fuelTypeID': vehicleFuelTypeId,
'transmissionTypeID': vehicleTransmissionTypeId,
'propulsionTypeID': vehiclePropulsionTypeId,
'registerationDate': registerationDate,
'powerKW': powerKW,
'description': description
}
}
I am learning Node by developing an application that would hit the relevant server and extract its data.
Here, I am stuck as the relevant server demand to pass access token, and I'm not able to extract data successfully.
Here is my code
var options = {
method: 'GET',
url: 'any url',
auth : {
accessToken : "token here"
},
headers: {
'Accept': 'application/json'
}
}
But doing this i'm getting error Error: no auth mechanism defined
Access token seems to be perfect.
Sorry if this has been asked already but I cannot seem to find a straight answer.
Thanks for your efforts and time.
Try this :
var req = {
host: 'YOUR_URL',
method: 'GET',
headers: {
Authorization: your token
'Content-Type': 'application/json'
}
}
request(req, function(error, response, body) {
console.log('error:', error); // Print the error if one occurred
console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
console.log('body:', body);
}
I am trying to call a REST API endpoint from node.js, using the 'request'module. I keep getting a 401 invalid credentials response. Code is as follows:
var q = {
'boothNumber':'1400',
'databaseName':'demo',
'exhibitorId':'T19',
'comment':'N/A'
};
var options = {
url: 'https://api2.e-----d.com',
path: '/edgewebapi/ACTDev2/booths/hold',
method: 'PUT',
//headers: headers,
headers: { 'Authorization':'Basic VUdFUTdDZkY6RmJsb0QyWiQ='},
body: JSON.stringify(q)
}
request(options, function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log('Request successful.');
}
else {
console.log('Error = ' + error) ;
}
})
I have read every post on this site to try to solve it, tried every suggestion, including the 'auth' option below (in a headers object):
I tried using a headers object (below):
var headers = {
'Accept': 'application/json',
'Authorization': 'Basic VUdFUTdDZkY6RmJsb0QyWiQ='
/*
'auth': {
'user': 'UGEQ7CfF',
'pass': 'FbloD2Z$',
'sendImmediately': false
}
*/
}
I retried using axios, code below, and everything works. (I really need to keep using the request module though, because I am using this in AWS Lambda and the axios causes me other issues...):
axios.put(
'https://api2.e---d.com/edgewebapi/ACTDev2/booths/hold?boothNumber=1400&databaseName=demo&exhibitorId=T19',
{},
{ headers : {'Authorization': 'Basic VUdFUTdDZkY6RmJsb0QyWiQ=' } }
).then(function(response) {
console.log(response.status);
}).catch(function(error) {
console.log(error);
});
Can anyone help by providing the correct code to do this? I have spent days trying to figure it out. Thanks.
I'm using a forEach loop to make a request to two different paths, but, although it does console.log() both bodyResponses, it gives error when trying to save it to render "index.ejs" with its value. (index.ejs is the template I wanna render):
manyPaths.forEach(function (element){
var signature = crypto.createHmac('sha256', apiSecret).update(verb + element.path + expires).digest('hex');
var headers = {
'content-type' : 'application/json',
'Accept': 'application/json',
'X-Requested-With': 'XMLHttpRequest',
'api-expires': expires,
'api-key': apiKey,
'api-signature': signature
};
const requestOptions = {
headers: headers,
url:'https://testnet.bitmex.com'+element.path,
method: verb
};
request(requestOptions, function(error, response, bodyResponse) {
if (error) {
console.log(error);
} else {
console.log(bodyResponse);
bodyResponse=JSON.parse(bodyResponse);
res.render("index", {bodyResponse:bodyResponse});
}
});
});
it does console.log both responses, but I get this error for render():
Error: Can't set headers after they are sent.
You can respond to a HTTP request only ONCE. So in your FOR loop, the first response is sent,and the connection is closed, and when it comes to the second iteration it fails with the error you see.
You have to wait for both calls to complete in parallel, and then kick of a function to send the response .
Using request module, I am trying to fetch response from a web service which has following header in the API request:
accept-encoding : gzip
and correspondingly, following header in the response :
content-encoding : gzip
When I am trying to decompress the response(get the correct readable response) using zlib(referred here), I am unable to do so.
Code Snippet :
var options = {
url: url,
qs: params.qparams,
method: params.method,
json: params.body,
headers: {
'api_key': configkey,
'Content-Type': 'application/json',
'Accept-Encoding': 'gzip'
},
timeout: constants.request_timeout
};
request(options, function(err, response, body) {
var encoding = response.headers['content-encoding']
if (encoding && encoding.indexOf('gzip') >= 0) {
zlib.gunzip(body, function(err, dezipped) {
//ERROR : { [Error: incorrect header check] errno: -3, code: 'Z_DATA_ERROR' }
var json_string = dezipped.toString('utf-8');
var json = JSON.parse(json_string);
console.log('\nJSON ::\n',json);
});
} else {
console.log('\n\nRESPONSE IS NOT GZIPPED!');
}
}
I am getting an error here(as commented in the code), using zlib.
I could not figure out as where is it going wrong, tried with multiple npm modules like unzipResponse and compress-buffer and tried different approaches as well as suggested at various places for handling gzip.
If someone can help out in resolving this, I'll be really thankful.
I have got a solution as need to add one more key to the options object as :
var options = {
url: url,
qs: params.qparams,
method: params.method,
json: params.body,
headers: {
'api_key': configkey,
'Content-Type': 'application/json',
'Accept-Encoding': 'gzip'
},
timeout: constants.request_timeout,
encoding: null
};
If someone has a better approach to perform the decompression, please add-on.