-1

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?

  • 4
    You should just take the time to read the [`http.request()`](https://nodejs.org/dist/latest-v6.x/docs/api/http.html#http_http_request_options_callback) docs from the Node.js Code – peteb Sep 15 '16 at 23:34
  • Thanks for the link! – Blender Noob Sep 15 '16 at 23:40
  • Also, the [request module](https://github.com/request/request) makes things even easier which you can install with `npm install request`. – jfriend00 Sep 15 '16 at 23:47

1 Answers1

1

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());
    }
});
jfriend00
  • 683,504
  • 96
  • 985
  • 979