Blender Noob Blender Noob - 2 months ago 21
Javascript Question

Node.js JavaScript Basic Get Request

Just installed node.js, and I'm having trouble sending basic get requests. I used to run things in chrome/firefox's console but wanted to branch out. What I am trying to do (as a test) is send a get request to a webpage, and have it print out some text on it.

In chrome's console, I would do something like this:

$.get("http://stackoverflow.com/questions/1801160/can-i-use-jquery-with-node-js", function(data) {
console.log($(data).find(".question-hyperlink")[0].innerHTML);
});


In node.js, how would I do that? I've tried requiring a few things and gone off a few examples but none of them worked.

Later on, I'll also need to add parameters to get and post requests, so if that involves something different, could you show how to send the request with the parameters {"dog":"bark"}? And say it returned the JSON {"cat":"meow"}, how would I read/get that?

Answer

You can install the request module with:

npm install request

And, then do this in your node.js code:

const request = require('request');

request.get("http://stackoverflow.com/questions/1801160/can-i-use-jquery-with-node-js", function(err, response, body) {
    if (err) {
        // deal with error here
    } else {
        // you can access the body parameter here to see the HTML
        console.log(body);
    }
});

The request module supports all sorts of optional parameters you can specify as part of your request for everything from custom headers to authentication to query parameters. You can see how to do all those things in the doc.

If you want to parse and search the HTML with a DOM like interface, you can use the cheerio module.

npm install request
npm install cheerio

And, then use this code:

const request = require('request');
const cheerio = require('cheerio');

request.get("http://stackoverflow.com/questions/1801160/can-i-use-jquery-with-node-js", function(err, response, body) {
    if (err) {
        // deal with error here
    } else {
        // you can access the body parameter here to see the HTML
        let $ = cheerio.load(body);
        console.log($.find(".question-hyperlink").html());
    }
});