Having trouble using "request"


#1

Hi, I am new to node.js, so this might be a silly question. I am having erratic response when using the following code. I did include “request” package in package.json. On rare occsations this works and shows google’s homepage but most time the “Log” icon keeps spinning. What will be the a reliable way to fetch content from a remote URI?

var request = require('request');

request('http://www.google.com', function (error, response, body) {

  console.log('error:', error); // Print the error if one occurred
  console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
  console.log('body:', body); // Print the HTML for the Google homepage.

});

#2

The log icon will continue to spin because Gltich is expecting a port to be opened up for web browsing, if your project is just the request code you provided Glitch will restart it over and over. You can try updating the default project to be something like:

// server.js
// where your node app starts

// init project
var express = require('express');
var app = express();

// listen for requests :)
var listener = app.listen(process.env.PORT, function () {
  console.log('Your app is listening on port ' + listener.address().port);
});


var request = require('request');

request('http://www.google.com', function (error, response, body) {

  console.log('error:', error); // Print the error if one occurred
  console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
  console.log('body:', body); // Print the HTML for the Google homepage.

});

This should allow the instance to start all the way up yet still grab the HTML you want and write it to the log window.


#3

Makes perfect sense. Thank you!