Nodejs https请求

Nodejs https请求
一.为什么用https请求
在跟网络交互时,我们往往会想到HTTPS协议,因为它增加了数据加密,更安全,在数据进行传输之前,对数据进行加密,然后再发送到服务器。
http 模块和 https 模块 比较
http :由 http、TCP、ip 组成
https:由 http、SSL/TLS、TCP、ip   组成
https 是基于 SSL 和 TLS 的 http 协议 
https 模块是用来专门处理加密访问的
所以https更安全,http 和 https 模块的 API 和使用方式几乎是一模一样的 ,差别是 https 在搭建服务器的时候要一个 SSL 证书
二.向安全的 Web 服务器发出请求。
options 可以是对象、字符串、或 URL 对象
1.Get请求:
const https = require('https');

const options = {
  hostname: 'encrypted.google.com',
  port: 443,
  path: '/',
  method: 'GET'
headers: {
        'username': 'admin',
        'password': '123456************',
        'Cookie': 'locale=zh_CN',
        'X-BuildTime': '2015-01-01 20:04:11',
        'Autologin': '4',
        'Accept-Encoding': 'gzip, deflate',
        'X-Timeout': '3600000',
        'Content-Type': 'Application/json',
        "Content-Length":reqdata.length
    }

};

const req = https.request(options, (res) => {
  console.log('状态码:', res.statusCode);
  console.log('请求头:', res.headers);

  res.on('data', (d) => {
    process.stdout.write(d);
  });
});

req.on('error', (e) => {
  console.error(e);
});
req.end();
2.post请求

var post_data="………………";//请求数据
var reqdata = JSON.stringify(post_data);//JSON解析成字符串

const https = require('https');

const options = {
  hostname: 'encrypted.google.com',
  port: 443,
  path: '/',
  method: 'POST’
};

const req = https.request(options, (res) => {
  console.log('状态码:', res.statusCode);
  console.log('请求头:', res.headers);

  res.on('data', (d) => {
    process.stdout.write(d);
  });
});

req.on('error', (e) => {
  console.error(e);
});
req.write(reqdata);//写入请求数据
req.end();

三.携带证书的https请求
Key:公钥
Cert:证书
const options = {
  hostname: 'encrypted.google.com',
  port: 443,
  path: '/',
  method: 'GET',
  key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),
  cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem')
};

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值