nodejs程序在服务器运行,使用https协议

nodejs程序使用https协议

  1. 在node程序文件夹中安装https模块、js的操作文件模块fs、路径模块path

    npm install https fs path --save
    
  2. 把ssl证书放到一个文件夹里,需要在程序之中引用
    在这里插入图片描述

  3. 在入口文件(如我的入口文件是app.js)引入https、fs、path

    const https=require("https");
    const fs= require('fs');
    const path=require('path');
    
  4. 把ssl证书文件导入

//key文件
const privateKey=fs.readFileSync(path.join(__dirname,'./httpsKeys/2_24years.top.key'),'utf8');
//crt文件
const certificate =fs.readFileSync(path.join(__dirname,'./httpsKeys/1_24years.top_bundle.crt'),'utf8');
const credentials = {
  key: privateKey,
  cert: certificate,
}
  1. 使用导入的ssl证书创建一个https站点
//app是创建的express实例
const httpsServer = https.createServer(credentials, app)
  1. 然后就可以设置运行端口了
httpsServer.listen(port, () => {
  console.log(`listening on port:${port}`);
});
  1. 需要运行时使用node app.js就行了

    在服务器上运行可以使用pm2模块运行app.js,好处是,可以保持后端程序一直运行,不论你是否退出远程连接
    首先要全局安装pm2模块

    npm i -g pm2
    

然后就可以使用pm2 start app.js运行项目了

完整代码

const express = require("express");
const http=require("http");
const https=require("https");
const fs = require('fs')
const path = require('path');
const privateKey=fs.readFileSync(path.join(__dirname,'./httpsKeys/2_24years.top.key'),'utf8');
const certificate =fs.readFileSync(path.join(__dirname,'./httpsKeys/1_24years.top_bundle.crt'),'utf8');
const credentials = {
  key: privateKey,
  cert: certificate,
}


const app = express();
const router = require("./router.js");
const httpsServer = https.createServer(credentials, app)
const port = process.env.PORT || 4000;

app.use("/api/*", function (req, res, next) {
  // 设置请求头为允许跨域
  res.header("Access-Control-Allow-Origin", "*");
  // 设置服务器支持的所有头信息字段
  res.header(
    "Access-Control-Allow-Headers",
    "Content-Type,Content-Length, Authorization, Accept,X-Requested-With"
  );
  // 设置服务器支持的clear所有跨域请求的方法
  res.header("Access-Control-Allow-Methods", "POST,GET");
  // next()方法表示进入下一个路由
  next()
});
//json化
app.use(express.urlencoded({ extended: false }));
app.use(express.json());
//访问后端node程序运行的根路径时,给客户端返回一条信息
app.get("/", (req, res) => {
  res.send({ msg: "您不能进入这儿" });
});
app.post("/", (req, res) => {
  res.send({ msg: "您不能进入这儿" });
});


// 注册登录、业务入口从这进去,/api
app.use("/api", router);
httpsServer.listen(port, () => {
  console.log(`listening on port:${port}`);
});

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值