美文网首页
node本地搭建http和https服务

node本地搭建http和https服务

作者: 知晓报到 | 来源:发表于2023-06-05 15:55 被阅读0次

前端开发经常需要本地启动服务用来调试页面或者代理数据,下面分别实现http和https两种方式

http服务搭建

1.在空文件夹内新建server.js文件,内容如下

const http = require("http");

const server = http.createServer((req, res) => {

  res.writeHead(200, { "Content-Type": "text/html;charset=utf8" });

  res.end("访问成功");

});

server.listen(8001, () => {

  console.log("服务已开启");

});

2.运行server.js

node server.js

3.浏览器访问

http://localhost:8001

https服务搭建

生成证书和密钥,证书构建基于mkcert工具,例子基于macOS系统

1.安装mkcert

brew install mkcert

2.生成根证书

mkcert -install

3.创建空文件夹

创建一个空文件夹用于储存生成的密钥和证书

mkdir ca

cd ca

4.生成所需域名需要的证书和密钥

mkcert test.mkcert.abc.com

执行成功后在ca文件夹下会生成 test.mkcert.abc.com-key.pem 和 test.mkcert.abc.com.pem 两个文件

5.在ca文件夹下创建server.js文件,内容如下

const https = require("https");

const fs = require("fs");

const path = require("path");

const options = {

  key: fs.readFileSync(

    path.join(__dirname, "./test.mkcert.abc.com-key.pem")

  ),

  cert: fs.readFileSync(path.join(__dirname, "./test.mkcert.abc.com.pem")),

};

const server = https.createServer(options, (req, res) => {

  res.writeHead(200, { "Content-Type": "text/html;charset=utf8" });

  res.end("访问成功443");

});

server.listen(443, () => {

  console.log("服务已开启");

});

6.修改/etc/hosts文件

加入

127.0.0.1 test.mkcert.abc.com

浏览器访问test.mkcert.abc.com

相关文章

  • node搭建本地代理解决ajax的跨域问题

    用到的技术 nodejs搭建本地http服务器 应用node-http-proxy,做接口url的转发 搭建过程 ...

  • 本地启动服务看vue应用在线上的效果

    使用http-server 使用express搭建本地node服务 npm install -g express-...

  • node启动https服务

    node.js可以在安装了http-server后,在本地起服务。但只能启动http服务,启动https服务需要密...

  • Node.js 之 http模块

    http模块 引入http模块 开启一个本地服务器需要Node.js中http核心模块http--模块提供了搭建本...

  • Node

    Node 检测Node是否安装成功 Node文件 自己搭建HTTP服务 创建http服务 监听端口 读取文件

  • 本地node.js服务器搭建

    本地node.js服务器搭建并通过浏览器访问服务器 github下载express https://github....

  • [头参数]01 - 搭建服务器

    目录 使用node搭建http服务端 1. 使用node搭建http服务端 代码 response.end来返回数...

  • Node.js 静态服务器新知

    用node http模块搭建服务器一直被用作项目实践及开发,深入学习后,对node搭建http服务器有了新的了解和...

  • Node.js Web 模块

    Node.js 提供了 http 模块,http 模块主要用于搭建 HTTP 服务端和客户端,使用 HTTP 服务...

  • nginx

    node 使用 nginx 反向代理搭建https服务 使用自己生成的证书 nginx http配置 编辑ngin...

网友评论

      本文标题:node本地搭建http和https服务

      本文链接:https://www.haomeiwen.com/subject/wtfwedtx.html