node.js发送https或http请求时可接收参数及出现的bug总结

发送http请求注意事项

在使用node.js发送http或https请求时,需注意:
如果是发送http请求,需要导入的node模块是:const http = require(‘http’);
如果是发送https请求,需要导入的node模块是:const https = require(‘https’);
两者是分开导入的。

发送http请求可接收的参数

  1. 发送http请求时,接收参数:
    option 数组对象,包含以下参数:

    host: 表示请求网站的域名或IP地址(请求的地址)。 默认为’localhost’。

    hostname: 服务器名称,主机名是首选的值。

    port: 请求网站的端口,默认为 80。

    localAddress: 建立网络连接的本地

    socketPath: Unix Domain Socket(Domain套接字路径)

    method: HTTP请求方法,默认是 ‘GET’。

    path: 请求的相对于根的路径,默认是’/’。QueryString应该包含在其中。例如:/index.html?page=12

    headers: 请求头对象。

    auth: Basic认证(基本身份验证),这个值将被计算成请求头中的 Authorization 部分。

    callback : 回调,传递一个参数,为 http.ClientResponse的实例。http.request 返回一个 http.ClientRequest 的实例。

  2. 发送https请求时,接收参数与http的类似,详情可见node.js官方文档:https://nodejs.org/dist/latest-v9.x/docs/api/https.html

发送http请求出现的bug总结

  • 1 Error: getaddrinfo ENOTFOUND https://xx.dd.com
    这里写图片描述

    解决方法:在node.js中使用http或者https发送请求的时候host不要带http://或者https://,直接写xx.yy.com即可。

  • 2 Error: write EPROTO 101057795:error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol:openssl\ssl\s23_clnt.c:825:
    这里写图片描述

    解决方法:使用https的时候的默认端口是443,如果在设置端口的时候设置成了80(使用http的默认端口是80)会报此错误。改成443或者server定义的https的端口即可。

  • 3 Error: unable to verify the first certificate
    <img src="111/png"/>

今天npm install总是报错:unable to verify the first certificate(无法验证第一证书),查了一下发现

As of February 27, 2014, npm no longer supports its self-signed certificates.
2014年2月27日,npm不再支持自签名证书。

因为npm install走的是https协议,需要通过数字证书来保证的。
(1) 解决方法1:
取消ssl验证:npm config set strict-ssl false;
如果还没成功,则将npm源更换为国内镜像:
npm config set registry http://registry.cnpmjs.org/
npm config set registry http://registry.npm.taobao.org/
(2)解决方法2:
在发送https请求的时候指定忽略证书验证,即options的rejectUnauthorized参数设置为false

    var https = require('https'); 
    var options = { 
      hostname: 'encrypted.google.com', 
      port: 443, 
      path: '/', 
      method: 'GET', 
      rejectUnauthorized:false
    }; 
    var req = https.request(options, function(res) { 
      console.log("statusCode: ", res.statusCode); 
      console.log("headers: ", res.headers); 
      res.on('data', function(d) { 
        process.stdout.write(d); 
      }); 
    }); 
    req.end(); 
    req.on('error', function(e) { 
      console.error(e); 
    }); 
  • 7
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值