http 模块和 https 模块
http 由 http TCP ip 组成
https 由 http
SSL/TLS
TCP ip 组成
https 是基于 SSL 和 TLS 的 http 协议
https 是在 http 是基础上 加入了
SSL 和 TLS
“握手” 以及数据加密传输
https 模块是用来专门处理加密访问的
http 和 https 模块的 API 和使用方式几乎是一模一样的 ,差别是 https 在搭建服务器的时候要一个 SSL 证书
搭建http服务器
const http = require('http'); //创建服务器 http
const hostname = '127.0.0.1'; //IP地址
const port = 3000; //端口号
const server = http.createServer((req, res) => { //监听到请求后,回调 function req 请求相关的信息(如:从哪来过来的,类型是get还是post等信息)
// res 告诉服务器给这个请求响应的内容
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain'); // 返回的请求头 200 成功 文本内容Content-Type 是 text/plain
res.end('Hello World\n'); //返回的内容,改变内容的重启服务 ctrl+c关掉, 再重启 node server.js
});
//listen 监听 来自 127.0.0.1 3000 的请求
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
执行方法,以上代码写在 server.js 文件里
cmd 打开命令,cd 进该js文件,然后
node server.js
,出现以下,其中的
http://127.0.0.1:3000/
就是地址
在浏览器中可以打开后出现返回的
Hello World
,这就是一个简单的服务
搭建https服务器
注意:要创建服务器端证书 ,options 就是证书
var https = require('https'); //创建服务器 https
var fs = require('fs'); //文件系统的模块
const hostname = '127.0.0.1';
const port = 3000;
var options = {
key : fs.readFileSync('ssh_key.pem'), //读出 sytly 文件?
cert : fs.readFileSync('ssh_cert.pem'), //同步读出 SSL 证书
}
const server = http.createServer(options ,(req, res) => { //监听到请求后,回调 function req 请求相关的信息(如:从哪来过来的,类型是get还是post等信息)
// res 告诉服务器给这个请求响应的内容
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain'); // 返回的请求头 200 成功 文本内容Content-Type 是 text/plain
res.end('Hello World\n'); //返回的内容,改变内容的重启服务 ctrl+c关掉, 再重启 node server.js
});
//listen 监听 来自 127.0.0.1 3000 的请求
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
总结:
http 和 https 模块的 API 和使用方式几乎是一模一样的 ,差别是 https 在搭建服务器的时候要一个 SSL 证书