invoke restful api in node.js - node.js

I have a method in my routes and I want to invoke the API mentioned in the uri. I am able to invoke the method successfully.But now I have created a method sample in my restful API in which I need to pass a value from node.js and print the concatenated value.
I have the sample method which accepts a String argument.I have created a variable named paramater = Hi and send this as an request.But it is not concatinating it.
Can anyone tell me the way to pass values in restful API in node.js
Here's mine code
router.post('/restful', function (req, res) {
var options = {
uri: 'http://192.168.1.6:8080/sampleRest/RequestxARC/sample',
method: 'post'
};
var parameters = "Hi";
var responseFromClient = '';
request(options, function (error, response, body, parameters) {
if (!error && response.statusCode == 200) {
responseFromClient = body;
}
else {
responseFromClient = 'Not Found';
}
console.log(responseFromClient);
//res.json(resss);
req.flash('response_msg', responseFromClient);
if (responseFromClient != 'Not Found') {
res.redirect('/users/restful');
}
else {
res.redirect('/users/restful');
}
});
});

If we want to use any value which is being passed from UI. We can use it by this way:
router.post('/restful', function(req, res){
var platformname=req.body.platform;//This is the way to attach variables from UI.
var options = {
uri : 'http://192.168.1.6:8080/sampleRest/RequestxARC/sample',
body : platformname,
method : 'post'
};
console.log(options.body +" value attached from UI");
var responseFromClient = '';
request(options,function (error, response, body ,form ,callback) {
if (!error && response.statusCode == 200) {
responseFromClient = body;
}
else {
responseFromClient = 'Not Found';
}
console.log(responseFromClient);
//res.json(resss);
req.flash('response_msg', responseFromClient);
if(responseFromClient !='Not Found'){
res.redirect('/users/restful');
}
else{
res.redirect('/users/restful');
}
});
});

Related

Node Js get data from URL and pass to new variable

I have created one NODE JS URL request to get JSON and pass it to the new variable var1.
Var1 can get data within request function when call var1 outside of request it returns null value why? how to get data from URL request and pass it to a new variable outside the Request URL?
function datadata() {
var var1 = 0;
var request = require('request');
request('http://x.x.x.x/json', function (error, response, body) {
if (!error && response.statusCode == 200) {
var importedJSON = JSON.parse(body);
var1 = importedJSON.result.data;
// show value of var1
console.log(var1);
}
});
// cannot show value of var1
console.log(var1);
return var1;
}
function datadata(){
var var1 = 0;
var request = require('request');
return new Promise(function(resolve, reject){
request('http://x.x.x.x/json', function (error, response, body) {
if (err) return reject(err);
try {
if (!error && response.statusCode == 200) {
var importedJSON = JSON.parse(body);
var1 = importedJSON.result.data;
console.log(var1);
} catch(e) {
reject(e);
}
});
});
}
datadata().then(function(res) {
console.log(res);
}).catch(function(err) {
console.err(err);
});
you can't get something outside the request that easy anyway you can try to use Promise
Example
const request = require('request');
var p = new Promise((resolve, reject) => {
request('http://x.x.x.x/json', function (error, response, body) {
if (!error && response.statusCode == 200) {
var importedJSON = JSON.parse(body);
resolve(importedJSON.result.data)
}
});
p.then((data) => {
console.log(data);
})
You can use a callback to the datadata like so
Check whether the body is found on the response, in that case change your code to
request('http://x.x.x.x/json', function (error,response) {
and
var importedJSON = JSON.parse(response.body);
You should do this because your importedJSON may not be having data because according to your code it's data comes from (body)
Mostly likely the json data will be found on the response.body.
Then we callback the specific data you want, in your case it's result.data. Again make sure the result.data can be found on the raw json data that the request gives you otherwise it won't output anything because there's nothing to output, most likely you will get errors
function datadata() {
var var1 = 0;
var request = require('request');
request('http://x.x.x.x/json', function (error,body,response) {
if (error && response.statusCode == 200) {
callback("There was an error")
}else{
var importedJSON = JSON.parse(body);
callback(importedJSON.result.data);
// show value of var1
console.log(var1);
});
}
datadata((error, var1) => {
if(error){
return console.log(error)
}
console.log(var1
})

How to call rest api in express js

I am new in nodejs and I am using express js, I am calling REST API and want to show the response, but my problem is that the response is showing in console.log but I want to pass the body(response) in assistant.ask, where I am wrong here is my code:
var request = require('request');
let rawInput = function (assistant) {
let rawInput = assistant.getRawInput();
request.post(
'http://xxxxxxx.ngrok.io/api/v1/240/respond',
{ json: { query: rawInput } },
function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body);
assistant.ask(body);
}
else{
console.log(error);
}
}
);

Meteor.call returns 'undefined' result when the variable is defined on server

Can somebody see in my code why the variable oauthToken is defined on the server but not defined when returned to the client in the result of Meteor.call
I make a call to initiate a post request on the server
The body is parsed and I store a value into the variable oauthToken
This prints out on the server but does not print out on the client in my 'result'
Is this because the client is running a simulation? Can we do a 'return' in an asynchronous function?
Server.js
Meteor.methods({
getGoodreads: function () {
request.post('http://www.goodreads.com/oauth/request_token', {oauth:{
consumer_key: '89hdg8pEoMzRdg',
consumer_secret: 'dfgdfgHthtdtjtt' }}, function (error, response, body) {
if (!error && response.statusCode == 200) {
var a = querystring.parse(body)
oauthToken = a.oauth_token
console.log(oauthToken); //prints value i need
return oauthToken
}else{
console.log('there is an error ' + error);
}
});
}
});
client.js
Template.profile.events({
'click #goodreads': function (event) {
event.preventDefault();
Meteor.call('getGoodreads', function(error, result) {
if (error) {
console.log('this is an error ');
} else {
console.log(result); //THIS IS UNDEFINED...possibilities?
}
});
}
});
Use futures to return values from async functions:
var Future = Npm.require("fibers/future")
Meteor.methods({
getGoodreads: function () {
var f = new Future();
request.post('http://www.goodreads.com/oauth/request_token', {oauth:{
consumer_key: '89hdg8pEoMzRdg',
consumer_secret: 'dfgdfgHthtdtjtt' }}, function (error, response, body) {
if (!error && response.statusCode == 200) {
var a = querystring.parse(body)
oauthToken = a.oauth_token
console.log(oauthToken); //prints value i need
return f.return(oauthToken)
}else{
f.throw(error);
console.log('there is an error ' + error);
}
});
return f.wait()
}
});
It's because you are starting an asynchronous request in the method body. The method returns immediately, and the callback from the request doesn't really have anywhere to return the result.
I don't really know how to do this with methods, but you could do it with publish/subscribe. Something like this:
Server.js
var result = "";
Meteor.setInterval(function() {
request.post('http://www.goodreads.com/oauth/request_token', {oauth:{
consumer_key: '89hdg8pEoMzRdg',
consumer_secret: 'dfgdfgHthtdtjtt' }},
function(error, response, body) {
if (!error && response.statusCode == 200) {
var a = querystring.parse(body);
oauthToken = a.oauth_token;
result = oauthtoken;
}
});
});
}, 10*1000);
Meteor.publish("goodReads", function() {
this.added("goodReads", 1, {reads: result});
Meteor.setInterval(function() {
this.changed("goodReads", 1, {reads: result});
}, 10*1000);
this.ready();
});
Client.js
goodReads = new Meteor.Collection("goodReads");
Meteor.subscribe("goodReads"); // May be done in waitOn in the router
This was taken off the top of my head, and is not tested. It may or may not work, but is at least a pointer to how you could do it

getting data from callbacks using node "request" library

I'm struggling with working out how to get the return data from this code example. If I try to get the cert data from the callback function its always empty. Is there something I'm missing here?
var Request = require('request');
function callhttp(host) {
var cert = " ";
var options = {
url: 'https://' + host
};
function callback(error, response, body) {
if (!error && response.statusCode == 200) {
var cert = response.connection.getPeerCertificate();
}
}
Request(options, callback);
return cert
}
console.log(callhttp("www.google.com"));
Best Regards.
By returning 'cert' you refer to the operation as a sync one, which is not.
The correct pattern is to pass a callback function and handle the data whitin:
var Request = require('request');
function callhttp(host, cb) {
var cert = " ";
var options = {
url: 'https://' + host
};
function callback(error, response, body) {
if (!error && response.statusCode == 200) {
var cert = response.connection.getPeerCertificate();
cb(cert);
}
}
Request(options, callback);
}
callhttp("www.google.com", function(_cert) {
console.log(_cert);
});

Change variable value within async function - node.js

var url = posts.paging.next;
for (var i = 0; i < 3; i++) {
(function(url,i) {
request(url,{json:true}, function (error, response, body) {
if (!error && response.statusCode == 200) {
url = body.paging.next;
console.log(i+"+++"+url)
}
});
})(url,i);
};//for
According to async request response (body.paging.next), İ want to change value of var url which is top of code .Please Help
NOTE: i'm trying to get all comments from facebook api , To do that , i need to get page links . Because of this , i wrote this codes , if you have any other alternative way please suggest them thanx
Assuming that you're trying to perform the requests in sequence (e.g. the next request relies on the url from the previous request), you could do something like (using the async module):
var async = require('async');
// ...
var url = posts.paging.next, i = 0;
async.whilst(
function() { return i < 3; },
function(callback) {
++i;
request(url, { json: true }, function(err, response, body) {
// TODO: handle `err`
//return callback(err);
if (!err && response.statusCode === 200) {
url = body.paging.next;
console.log(i + '+++' + url);
callback();
}
});
},
function(err) {
// done!
}
);

Resources