发送http请求注意事项
在使用node.js发送http或https请求时,需注意:
如果是发送http请求,需要导入的node模块是:const http = require(‘http’);
如果是发送https请求,需要导入的node模块是:const https = require(‘https’);
两者是分开导入的。
发送http请求可接收的参数
发送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 的实例。
发送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
今天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); });