how to read response of simple http request made in node - javascript

I am using the request module in node to make an http request. How do I read the response content of that request so that I can make a programmatic decision based on the response?
gulp.task("run-server-tests", function(){
var responseJson = request("http://myurl/run-server-tests")
plugins.util.log(responseJson); // not sure how to get at the response json
});

request allows you to use callback function, see more detail
request('http://www.google.com', function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body) // Show the HTML for the Google homepage.
}
})

Related

Http Request inside forEach - NodeJS

I have spreadsheets with data that needs to be uploaded via an API. After extracting the data from the spreadsheet, I create an object and put it in an array.
My idea was to iterate over this array and make a request for every single object in there and use the status code to display a success or error message.
The code seems to work fine with small quantities (~ 200 elements) but when I try to stress it (lets say 3500 elements), the line response.statusCode breaks because response is undefined. I thought I wouldn't have any problems with the async part because the callback would be called only when the server responded, but it seems not to be the case here.
Why am I getting response undefined in a callback?
Here's a piece of code i'm using:
array.forEach(function (element) {
//Configure Request
var options = {
url: 'http://example',
method: 'POST',
headers: headers,
body: element,
json: true
}
request(options, function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(response.statusCode);
console.log(body)
} else {
console.log(response.statusCode);
console.log(error)
}
});
});
Thanks!
Please run this code in async.mapLimit()
https://caolan.github.io/async/docs.html#mapLimit

how to call webapi at server startup in NodeJS

I have created a get web api that i want to hit at my server startup for some specific task. I have used this method
var request = require('request');
request('http://localhost:3000/api/jobs/asd', function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body) // Print the google web page.
}
}
)
But i am getting status code as 403. So i am not able to access my API at serve startup. Please suggest me the proper solution for the same.
thanks in adv.
You can place your code inside http callback like so :
http.createServer(app).listen(3000, () => {
//your code here
});

Javascript - How to make REST API Calls

I am trying to access Firebase Database using REST API. Using cURL i am able to retrive data. I am unable to do the same in javascript.
cURL
curl 'https://testproject123.firebaseio.com/subscription.json?auth=aabbccddeeff123'
Javascript
var request = require('request');
var options = {
url: 'https://testproject123.firebaseio.com/subscription.json?auth=aabbccddeeff123' };
function callback(error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body);
} }
request(options, callback);
Note: The above code i am trying to run on Bluemix/OpenWhisk.
Kindly let me know how to fix this.
The structure of your action is a bit off for OpenWhisk. Javascript actions need to have a main method and you'll have to use whisk.async() and whisk.done() to make your (asynchronous) REST API call work as you'd expect it.
An example of how to call an external API using a Javascript action in OpenWhisk can be found here.

How to GET JSON Object from URL in Node.js/Express

I should preface my post by saying that I am a beginner and this is my first time using Node.js and Express in a real project.
I have a simple Node.js/Express project and I want to read a JSON object from a URL. Afterwards, I intend to build another url that displays html from an external website using iframe.
I read about the 'request' module online and know that I need to do something along these lines:
var express = require('express');
var router = express.Router();
var request = require('request');
// Urls for App Center REST functions
var url = 'https://someserver.com/appserver/portal/api/1.0/results/recent';
/* GET list of recent reports */
router.get('/testapi', function(req, res, next) {
res.render('testapi', { title: 'List Recent Reports' });
});
/* TEST: function to GET report list */
router.get('/recentreports', function(req, res){
request({
url: url,
json: true
}, function (error, response, body) {
if (!error && response.statusCode === 200) {
console.log(body) // Print the json response
}
})
});
I have tried to define a function /recentreports which is called in the testapi.jade view, however nothing is printed in the console when I load the page and I suspect I am doing something horribly wrong.
My questions are:
How do I read the JSON into my app and where does this code go (index.js, app.js, testview.jade etc...?)
How do I export the URL I construct from wherever that code lives to my .jade view?
There was nothing logged to the browser console because no response was sent from your server. The response was only logged to the server's console.
You'll need to refactor the code for the 'recentreports' route to send data. You could use a simple res.send call:
...
function (error, response, body) {
if (!error && response.statusCode === 200) {
res.send(body) // Send the response to the client
}
}
...
This response will be received by testapi.jade via an AJAX call to the '/recentreports' route. The AJAX call can be defined in a Javascript file sourced by the testapi.jade file.
The constructed URL would not need to be exported as it exists within the same testapi.jade file (after you've formed it from the results from the AJAX call).

Setting Language of API in NodeJS

I am trying to implement the DuckDuckGo Instant Answer Api into my NodeJS application.
For that I request data from the Api using Node Request.
var request = require('request');
request('http://api.duckduckgo.com/?q=Hamburg&format=json&pretty=1', function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(JSON.parse(body));
}
})
This gives me the result in English, but I would like to have it in German. In my browser it is in German. How can I change my code so I can get the data in German in NodeJS?
Thank you!
You can add the kad key with a proper locale.
As so:
http://api.duckduckgo.com/?q=Hamburg&format=json&pretty=1&kad=de_DE

Categories