首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在node.js中发出https请求

如何在node.js中发出https请求
EN

Stack Overflow用户
提问于 2015-01-18 08:34:57
回答 1查看 3.2K关注 0票数 1

我要做个爬虫。对于http请求,我曾经这样做过。

代码语言:javascript
复制
 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使用相同的爬虫,就会产生这个错误。

代码语言:javascript
复制
 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)
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-01-18 08:41:50

我推荐这个优秀的HTTP请求模块:http://unirest.io/nodejs.html

您可以通过以下方式安装它:

安装-g unirest

下面是一些使用Unirest的Node代码示例:

代码语言:javascript
复制
  var url = 'https://somewhere.com/';
  unirest.get(url)
    .end(function(response) {
      var body = response.body;
      // TODO: parse the body
      done();
    });

若要在...so上获取www.purple.com,请执行以下操作:

代码语言:javascript
复制
#!/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);
});
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28008393

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档