nodejs程序使用https协议
-
在node程序文件夹中安装https模块、js的操作文件模块fs、路径模块path
npm install https fs path --save
-
把ssl证书放到一个文件夹里,需要在程序之中引用
-
在入口文件(如我的入口文件是app.js)引入https、fs、path
const https=require("https"); const fs= require('fs'); const path=require('path');
-
把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,
}
- 使用导入的ssl证书创建一个https站点
//app是创建的express实例
const httpsServer = https.createServer(credentials, app)
- 然后就可以设置运行端口了
httpsServer.listen(port, () => {
console.log(`listening on port:${port}`);
});
-
需要运行时使用
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}`);
});