为什么Node.js中的“请求模块”只接受用协议写的URL?

时间:2021-02-28 16:58:43

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

我想使用请求模块发送GET请求。这是代码:

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.

但它不起作用,因为myUrlObj的“协议”属性为空值。

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.

但有些网站使用https,而其他网站则使用http。因此,对于使用https的网站,上述代码失败,并且require模块抛出异常。

1 个解决方案

#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.

如果URL来自用户输入,则默认为http://并让他们输入HTTPS协议。鼓励他们输入协议。大多数HTTPS网站会将您从HTTP网址重定向到HTTPS网址。您可以使用此处的示例使请求模块遵循重定向。

#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.

如果URL来自用户输入,则默认为http://并让他们输入HTTPS协议。鼓励他们输入协议。大多数HTTPS网站会将您从HTTP网址重定向到HTTPS网址。您可以使用此处的示例使请求模块遵循重定向。