How to make a get request in nodejs - node.js

I'm trying make a get request to get user online in a channel on my server, but i always reveive all user of my server.
I have used request module, but it not working, seem it not pass parameter "_id" on request
in curl
curl -s -G \
-H "X-Auth-Token: Qv5vMPB_6aMCSv5ayQAbQCXkSsBzra_K6BbAqc7S0Fr" \
-H "X-User-Id: 34YYb2cqqDaFz53ib" \
-H "Accepts: application/json" \
--data-urlencode 'query={"_id": "FC77kqfNrH39wEaKG"}' \
http://localhost:3001/api/v1/channels.online
result as I expert
{
"online": [
{
"_id": "D539dgygpWrYrNyFz",
"username": "tranhoang"
},
{
"_id": "34YYb2cqqDaFz53ib",
"username": "mybot"
}
],
"success": true
}
code use request module
var request = require('request');
var headers = {
'X-Auth-Token': 'Qv5vMPB_6aMCSv5ayQAbQCXkSsBzra_K6BbAqc7S0Fr',
'X-User-Id': '34YYb2cqqDaFz53ib',
'Accepts': 'application/json'
};
var options = {
url: 'http://localhost:3001/api/v1/channels.online',
headers: headers,
form: {
query: '{"_id": "FC77kqfNrH39wEaKG"}'
}
};
function callback(error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body);
console.log(response);
}
}
request(options, callback);
and result
{
"online": [
{
"_id": "D539dgygpWrYrNyFz",
"username": "tranhoang"
},
{
"_id": "34YYb2cqqDaFz53ib",
"username": "mybot"
},
{
"_id": "DkiEXfaXRA5EffnHb",
"username": "sp2"
}
],
"success": true
}
sp2 is not join in channel that have "_id" in form, what can i do, please help me!!

To make HTTP GET request in Node.js using request module, you don't need form in options object. Instead, qs in options is the right choice.
The code would look like:
var request = require('request');
var headers = {
'X-Auth-Token': 'Qv5v...S0Fr',
'X-User-Id': '34YY...53ib',
'Accepts': 'application/json'
};
var options = {
uri: 'http://localhost:3001/api/v1/channels.online',
headers: headers,
qs: {
query: {"_id": "FC77kqfNrH39wEaKG"}
},
method: 'GET'
};
function callback(error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body);
console.log(response);
}
}
request(options, callback);

Related

what is the nodejs code for this curl command

I can successfully execute this curl command from a Unix shell script and I can see output in C:\Users\OutputFile.csv. What is the equivalent code in NodeJS
curl -k -v --user 'helloworld:hello_password'
--header 'Accept: application/vnd.myDMS-dms-api+json; version=1'
-X POST 'https://DMS.com:3001/download/csv'
--data header=true -o C:\Users\OutputFile.csv
I tried using the Online curl to nodeJS converter and it has generated the following NodeJs code:-
var request = require('request');
var headers = {
'Accept': 'application/vnd.myDMS-dms-api+json; version=1'
};
var options = {
url: 'https://DMS.com:3001/download/csv',
method: 'POST',
headers: headers,
auth: {
'user': 'helloworld',
'pass': 'hello_password'
}
};
function callback(error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body);
}
}
request(options, callback);
However, when I run this NodeJS code it does not show any output. Also how can I get this output to C:\Users\OutputFile.csv
Maybe the response isn't return before the script is terminated. You would want the request to be asynchronous:
You can use request-promise
Here's an example
var rp = require('request-promise');
function someFunction() {
let options = {
url: `someURL`,
method: 'POST',
body: {
some: 'payload'
},
json: true
};
return rp(options);
}
This will await the response.
A simple version of your API parameters using request-promise:
var rp = require('request-promise');
function downloadFile() {
var options = {
uri: 'https://DMS.com:3001/download/csv',
method: 'POST',
auth: {
user: 'helloworld',
pass: 'hello_password',
sendImmediately: true
},
headers: {
Accept:'application/vnd.myDMS-dms-api+json; version=1'
},
form: {
'header': 'true'
}
};
rp(options)
.then(function (body) {
console.log('Downloaded body was %d long', repos.length);
})
.catch(function (err) {
console.log(err)
});
}
downloadFile()

Openfigi REST API in node js

I am trying to run the following Nodejs program to retrieve data from OpenFigi.
But, not getting any information whereas curl request returns the data.
var request = require('request');
var options = {
url: 'https://api.openfigi.com/v1/mapping',
data: '[{"idType":"ID_WERTPAPIER","idValue":"851399","exchCode":"US"}]',
headers: {
'Content-Type': 'text/json'
} };
function callback(error, response, body) {
if (!error && response.statusCode == 200) {
var info = JSON.parse(body);
console.log(info);
}
}
request(options, callback);
The following curl request returns the data
curl -v POST 'https://api.openfigi.com/v1/mapping' \
--header 'Content-Type: text/json' \
--data '[{"idType":"ID_WERTPAPIER","idValue":"851399","exchCode":"US"}]'
Result:
[
{
"data": [
{
"figi": "BBG000BLNNH6",
"securityType": "Common Stock",
"marketSector": "Equity",
"ticker": "IBM",
"name": "INTL BUSINESS MACHINES CORP",
"uniqueID": "EQ0010080100001000",
}
]
}
]
Could you please help to fix the nodejs program.
Thanks,
Saravana
You didn't give method type
var options = {
url: 'https://api.openfigi.com/v1/mapping',
method:'POST',
data: '[{"idType":"ID_WERTPAPIER","idValue":"851399","exchCode":"US"}]',
headers: {
'Content-Type': 'text/json'
} };

Can send post request with curl but cannot from a node server

I can make a post request to a REST api endpoint of a web service with curl successfully but couldnt do so with request module in node.js. Instead, I always get error CONNECTION ETIMEDOUT.What is the problem?
curl command:
curl -i --header "Content-Type: application/json" -XPOST 'http://<endpoint_url>/urls' -d '{
"callback": "http://www.example.com/callback",
"total": 3,
"urls": [ {
"url": "http://www.domain.com/index1.html"
}, {
"url": "http://www.domain.com/index2.html"
}, {
"url": "http://www.domain.com/index3.html"
}
]
}'
code:
function sendRequestToEndPoint() {
const sample = {
"callback": "http://www.example.com/callback",
"total": 3,
"urls": [ {
"url": "http://www.domain.com/index1.html"
}, {
"url": "http://www.domain.com/index2.html"
}, {
"url": "http://www.domain.com/index3.html"
}
]
}
const options = {
method: 'post',
//headers: {
// 'Content-Type': 'application/json',
// 'Accept': 'application/json',
//},
url: 'http://<endpoint_url>/urls',
json: sample
//body: JSON.stringify(sample) // also tried this with headers on
};
console.log(sample);
request(options, (error, response, body) => {
console.log(response)
});
}
Update: Turned out that it was because the api url I used is not correct.
use querystring to stringify your json data,
var querystring = require('querystring');
...
sample = querystring.stringify(sample);
look at this answer How to make an HTTP POST request in node.js
this code works,
you need to Stringify your json object using JSON.stringify , and use the methode write of the object request to send the sample json object
, http = require('http')
, bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: false
}));
var sample = JSON.stringify({
"callback": "http://www.example.com/callback"
, "total": 3
, "urls": [{
"url": "http://www.domain.com/index1.html"
}, {
"url": "http://www.domain.com/index2.html"
}, {
"url": "http://www.domain.com/index3.html"
}
]
});
var options = {
hostname: 'localhost'
, port: 80
, path: '/test/a'
, method: 'POST'
, headers: {
'Content-Type': 'application/json'
, 'Content-Length': sample.length
}
};
app.get('/', function (req, res) {
var r = http.request(options, (response) => {
console.log(`STATUS: ${response.statusCode}`);
console.log(`HEADERS: ${JSON.stringify(response.headers)}`);
response.setEncoding('utf8');
response.on('data', (chunk) => {
console.log(`BODY: ${chunk}`);
});
response.on('end', () => {
console.log('No more data in response.');
});
});
r.on('error', (e) => {
console.log(`problem with request: ${e.message}`);
});
r.write(sample);
r.end();
res.send('ok');
});
a link for more details about http.request nodejs.org http.request(options[, callback])

cURL call to API in NodeJS Request

it's me again with another lame question. I have the following call to a Rattic password database API which works properly:
curl -s -H 'Authorization: ApiKey myUser:verySecretAPIKey' -H 'Accept: text/json' https://example.com/passdb/api/v1/cred/\?format\=json
I tried to replicate this call in NodeJS, however the following returns blank:
var request = require('request');
url='https://example.com/passdb/api/v1/cred/?format=json';
request({
url: url,
method: 'POST',
headers: [
{ 'Authorization': 'ApiKey myUser:verySecretAPIKey' }
],
},
function (error, response, body) {
if (error) throw error;
console.log(body);
}
);
Any help is appreciated.
As pointed out in the comments already, use GET, not POST;
headers should be an object, not an array;
You're not adding the Accept header.
All combined, try this:
request({
url : url,
method : 'GET',
headers : {
Authorization : 'ApiKey myUser:verySecretAPIKey',
Accept : 'text/json'
}, function (error, response, body) {
if (error) throw error;
console.log(body);
}
});
One thing you can do is import a curl request into Postman and then export it into different forms. for example, nodejs:
var http = require("https");
var options = {
"method": "GET",
"hostname": "example.com",
"port": null,
"path": "/passdb/api/v1/cred/%5C?format%5C=json",
"headers": {
"authorization": "ApiKey myUser:verySecretAPIKey",
"accept": "text/json",
"cache-control": "no-cache",
"postman-token": "c3c32eb5-ac9e-a847-aa23-91b2cbe771c9"
}
};
var req = http.request(options, function (res) {
var chunks = [];
res.on("data", function (chunk) {
chunks.push(chunk);
});
res.on("end", function () {
var body = Buffer.concat(chunks);
console.log(body.toString());
});
});
req.end();
Headers should be an object.
var request = require('request');
url='https://example.com/passdb/api/v1/cred/?format=json';
request({
url: url,
method: 'POST',
headers: {
'Authorization': 'ApiKey myUser:verySecretAPIKey'
}
}, function (error, response, body) {
if (error) throw error;
console.log(body);
});

Trying to post api request

I having problem with making a API call to an external site.
I need to send a POST request to http://api.turfgame.com/v4/users with headers Content-type: application/js. But when I run this code it only loads and nothing more.
var request = require('request');
var options = {
uri: 'http://api.turfgame.com/v4/users',
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: {
"name": "username"
}
};
request(options, function (error, response, body) {
if (!error && response.statusCode == 200) {
res.send(response.body);
}
});
The body need to be posted in json formate [{'name': 'username'}].
Can someone tell me what I have done wrong?
There are a few things wrong:
the address property in the "options" object should be "url" not
"uri"
you can use the "json" property instead of body
"res" is undefined in your response handler function
if you want the body to be an array, it needs to be surrounded in square brackets
here's a working sample that just logs the response:
var request = require('request');
var options = {
url: 'http://api.turfgame.com/v4/users',
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
json: [{
"name": "username"
}]
};
request(options, function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(response.body);
}
});

Resources