如何在node.js中进行https请求
我需要做一个爬虫。 对于我用来做这个的http请求。
var http=require('http'); var options={ host:'http://www.example.com', path:'/foo/example' }; callback=function(response){ var str=''; response.on('data',function(chunk){ str+=chunk; }); response.on('end', function () { console.log(str); }); } http.request(options, callback).end();
但我必须为https://example.com/foo/example做一个爬虫如果我使用相同的https://example.com/foo/example它给这个错误
events.js:72 throw er; // Unhandled 'error' event ^ Error: getaddrinfo ENOTFOUND at errnoException (dns.js:37:11) at Object.onanswer [as oncomplete] (dns.js:124:16)
我推荐这个优秀的HTTP请求模块: http : //unirest.io/nodejs.html
你可以用下面的方法安装它
npm install -g unirest
下面是一些Unirest的例子:
var url = 'https://somewhere.com/'; unirest.get(url) .end(function(response) { var body = response.body; // TODO: parse the body done(); });
…所以要在www.purple.com得到HTML你会这样做:
#!/usr/bin/env node function getHTML(url, next) { var unirest = require('unirest'); unirest.get(url) .end(function(response) { var body = response.body; if (next) next(body); }); } getHTML('http://purple.com/', function(html) { console.log(html); });