Api integration with nodejs and to get the values - node.js

How to integrate api with nodejs?
Using api,i want to get all the values in nodejs
I want a detail coding for this.
Thanks in advance

shobana you can get results from any APIs using a curl or http request. Following is a code snippet you can give a try.
var request = require('request');
// Set the headers
var headers = {
'User-Agent': 'Super Agent/0.0.1',
'Content-Type': 'application/x-www-form-urlencoded'
}
// Configure the request
var options = {
url: 'url_link',
method: 'POST',
headers: headers,
form: {"key1":value1,"key2":value2,"key3":value3}
}
// Start the request
request(options, function (error, response, body) {
if (!error && response.statusCode == 200)
{
// Print out the response body
console.log(body)
}
})

Related

Pass post data to another url and get url response in post response

I am trying to pass some data to /card then filter it and send to a url and the final response of my /card need to be response send from the url.
app.post('/card', (req, res) => {
var testData = req.body.orderId;
if(testData!=null){
var options = {
uri: 'https://localhost',
headers: {'content-type' : 'application/json'},
method: 'POST',
json: {"longUrl": testData}
};
request(options, function (error, response, body) {
if (!error && response.statusCode == 200) {
// res.json(testData);
console.log(body.id) // Print the shortened url.
}
});
}
});
You can use Node.js core module http to make an http request from within your Node application.
You can consult the official documentation and various options here https://nodejs.org/api/http.html#http_http_request_options_callback

Can't get basic authentication in node.js/request module to work with PUT or POST request

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.

retrieve JSON response of a POST request in nodeJS

I am sending s POST request to a service and it is supposed to return a JSON in response. I see the POST is successful but I dont get anything in response back. What am I missing? Below code
var headers = {
"Accept":"application/json",
"Content-Type":"application/json",
"Authorization": ("Basic " + new Buffer("admin:password").toString('base64'))
}
// Configure the request
var options = {
url: 'myservice-url',
method : 'POST',
headers : headers
}
// Start the request
request(options, function (error, response, body) {
if (!error && response.statusCode == 200) {
// Print out the response body
var str = JSON.stringify(body, null, 2);
console.log(str)
}
})
First of all, need to confirm if you have properly installed the following:
https://github.com/request/request
Then require it in your file like this:
var request = require('request');
request.post({
url: "",//your url
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
rejectUnauthorized: false,//add when working with https sites
requestCert: false,//add when working with https sites
agent: false,//add when working with https sites
form: {
whateverfieldnameyouwant: "whatevervalueyouwant"
}
},function (response, err, body){
console.log('Body:',JSON.parse(body));
}.bind(this));

Sending an API request with Nodejs

I've been trying to hit an API and get some data back from it (It's a free API not my own). So I've got my API token and I've had a look around and found that npm package request seems to be the best.
Within one of my routes I have,
request({
uri: "https://app.url-to-api:443/api/list-of-data",
method: "GET",
api_token: "my-api-token",
timeout: 10000,
followRedirect: true,
maxRedirects: 10
}, function(error, response, body) {
console.log(body);
});
So I'm getting "message":"Authorization has been denied for this request." back which is obviously because my API Token isn't getting passed through.
This might be a stupid question, but where do I actually put the API token to validate my request?
Thanks!
In request it would be something like this:
request.get('http://some.server.com/', {
'auth': {
'bearer': 'bearerToken'
}
});
More details on what you can do with request are in the docs.
You have to pass api tokens in request headers please see the documentation for request
var request = require('request');
var options = {
url: 'https://api.github.com/repos/request/request',
headers: {
'Access-Token': 'request'
}
};
function callback(error, response, body) {
if (!error && response.statusCode == 200) {
var info = JSON.parse(body);
console.log(info.stargazers_count + " Stars");
console.log(info.forks_count + " Forks");
}
}
request(options, callback);

How to view request sent from node.js to server?

Regarding to this question:
Transfer / pass cookies from one request to another in nodejs/protractor
I got another one. How could I view complete request (headers + body) which I am performing via nodejs?
Yes, you can ... You can access the complete request from the full response body - response.request
I have a generic full response structure illustrated below
IncomingMessage
ReadableState
headers(ResponseHeaders)
rawHeaders
request - //This is what you need
headers
body
body(Response Body)
You can access through code as shown below
var request = require("request");
var options = { method: 'POST',
url: 'http://1.1.1.1/login',
headers:
{ 'cache-control': 'no-cache',
'content-type': 'application/json' },
body: { email: 'junk#junk.com', password: 'junk#123' },
json: true };
request(options, function (error, response, body) {
if (error) throw new Error(error);
// This will give you complete request
console.log(response.request);
//This gives you the headers from Request
console.log(response.request.headers);
});

Resources