How to call rest api in express js - node.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);
}
}
);

Related

Why I cannot get the data from body in request method

I try to get the JSON data from a GET request and I can see the information from body in request. How can I get the data?
Currently use NodeJs, basic in JavaScript.
var definedURL="https://api.etherscan.io/api?module=account&action=tokentx&contractaddress=0x6a750d255416483bec1a31ca7050c6dac4263b57&page=1&offset=100&sort=asc&apikey=YourApiKeyToken";
var request = require('request')
var information=[];
request({
url: definedURL,
json: true
}, function (error, response, body) {
if (!error && response.statusCode === 200) {
//console.log(body.result[0]);
information.push(body.result[0]);
}
});
console.log(information);
I expect after this I will see the contain of result coming out, but now it still shows [].
Because you are making asynchronous request. Asynchronous action will get completed after the main thread execution.
console.log(information) // execute before your call
You need to wait for the request call to get completed and received data get pushed to information
There can be two ways to do this -
Async/Await- MDN Reference
var definedURL="https://api.etherscan.io/api?module=account&action=tokentx&contractaddress=0x6a750d255416483bec1a31ca7050c6dac4263b57&page=1&offset=100&sort=asc&apikey=YourApiKeyToken";
var request = require('request')
var information=[];
async () => {
await request({
url: definedURL,
json: true
}, function (error, response, body) {
if (!error && response.statusCode === 200) {
//console.log(body.result[0]);
information.push(body.result[0]);
}
});
console.log(information)
}();
Promise MDN reference
var definedURL="https://api.etherscan.io/api?module=account&action=tokentx&contractaddress=0x6a750d255416483bec1a31ca7050c6dac4263b57&page=1&offset=100&sort=asc&apikey=YourApiKeyToken";
var request = require('request')
var information=[];
var Promise = new Promise((resolve,reject) => {
request({
url: definedURL,
json: true
}, function (error, response, body) {
if (!error && response.statusCode === 200) {
//console.log(body.result[0]);
information.push(body.result[0]);
resolve()
}
});
})
Promise.then(() => {
console.log(information)
})

How to make a post request using request module NodeJs express

How to make a proper post request to this endpoint. When I use the POSTMAN I get the correct response but when I call using the below function I get 503 error. The call seems to be fine according to me. I appreciate your help!!
const request = require('request');
const express = require('express');
// Initialize request
var img64Data = "/9j/4AAQSkZJRgABAQAAAQABAAD/2w… "; // Include the entire base64 encoding. // Shown Below in the next page
var send = {"img64": img64Data};
var api_address = "https://8n78hbwks0.execute-api.us-west-2.amazonaws.com/dev/";
// Make Post Request
module.exports = app => {
app.post('/axe', (req, res, next) => {
console.log("inside the axe");
request.post({
url: api_address,
body: JSON.stringify(send),
headers: {"Content-Type":"application/json"}
}, function (error, response, body) {
console.log("hiii");
console.log(response.statusCode);
if (!error && response.statusCode == 200) {
// Successful call
var results = JSON.parse(body);
console.log(results) // View Results
}
});
});
};
You get a 503 Error https://en.wikipedia.org/wiki/List_of_HTTP_status_codes because your server doesn't reply any http code.
if (!error && response.statusCode == 200) {
// Successful call
var results = JSON.parse(body);
console.log(results) // View Results
res.sendStatus(200);
} else {
res.sendStatus(response.statusCode);
}

invoke restful api in 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');
}
});
});

Accessing GET response body parameters

I am using the request package to make a simple HTTP GET request to the npm API. I am trying to get the download counts for npm packages from an arbitrary function in my nodeJS backend.
Here is my updateDownloadCount.ts file:
export function updateDownloads() {
plugin.find(function (err, plugins: Array<any>) {
for (let plugin of plugins) {
var url = 'https://api.npmjs.org/downloads/point/last-month/' + plugin.package;
request(url, function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body)
}
})
}
})
}
So that's fine and I get a string of outputs like:
{"downloads":17627637,"start":"2016-08-29","end":"2016-09-27","package":"request"}
however, when I try to access just the downloads count, i.e.
console.log(body.downloads);
I get undefined console logged... How can I access the body variables? I feel like this should be super simple, but I couldn't find any docs on it.
Try to parse body if it is string type
export function updateDownloads() {
plugin.find(function(err, plugins: Array < any > ) {
for (let plugin of plugins) {
var url = 'https://api.npmjs.org/downloads/point/last-month/' + plugin.package;
request(url, function(error, response, body) {
if (!error && response.statusCode == 200) {
if (body && typeof body == "string") {
body = JSON.parse(body);
}
console.log(body.downloads);
}
})
}
})
}

Returning a value from a function in node.js

Still learning node. Based upon the following:
https://github.com/request/request
var request = require('request');
request('http://www.google.com', function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body) // Show the HTML for the Google homepage.
}
})
I wish to create the above as a reusable block of code so thought I'd wrap it in a function passing the URL as a parameter such as:
var request = require('request');
var URL;
var request = require('request');
request('http://www.google.com', function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body) // Show the HTML for the Google homepage.
}
})
function fetchURL (URL) {
request(URL, function (error, response, body) {
if (!error && response.statusCode == 200) {
return body;
}
});
};
var a = fetchURL('http://www.google.com');
console.log(a);
This works however I am unsure of whether "return body" is needed as it also works without this line. Happy to received comments on my coding style too as it's all new to me.
The pattern in Node is to provide a callback as an argument to an asynchronous function. By convention, this callback function has error as its first argument. For example:
function fetchURL(url, callback) {
request(url, function(error, response, body) {
if (!error && response.statusCode == 200) {
callback(null, body);
} else {
callback(error);
}
});
};
fetchURL('http://www.google.com', function(err, body) {
console.log(body);
});
Note that in your snippet, return body; is a return from the anonymous callback function passed into fetchURL(). fetchURL() itself returns nothing.

Resources