0

I want to send a GET request using request module. Here's the code:

var requestModule = require('request');
var url = require('url');

var myUrl = 'www.google.com';
var myUrlObj = url.parse(myUrl); 

requestModule(myUrl, myUrlObj , callback);

but it doesn't work because myUrlObj has a null value for its "protocol" attribute.

The same code works when:

var myUrl = 'http://www.google.com'

Why is it so rigid?

Also I tried doing the following to get around this problem:

if ( myUrlObj.protocol == null ) {
    myUrl = "http://" + myUrl;
    myUrlObj = url.parse(myUrl);
}

But some websites use https, while others use http. So, the above code fails for websites that use https, and the require module throws an exception.

sga4
  • 350
  • 4
  • 15

1 Answers1

1

If the URL comes from user input, default to http:// and let them enter a protocol for HTTPS. Encourage them to enter a protocol. Most HTTPS websites will redirect you from the HTTP url to the HTTPS URL. You can make the request module follow redirects using the example here.

Community
  • 1
  • 1
Will
  • 24,082
  • 14
  • 97
  • 108