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')
};