怎么启用 https 的 node 服务?

1.创建一个文件夹 nodeServer
2.在Node.js项目中启用HTTPS,您需要生成一个SSL证书 (用于测试时)
// 安装
openssl req -nodes -new -x509 -keyout server.key -out server.cert

// 回车后出现 地区输入 CN 后面的一路回车即可
Country Name (2 letter code) [AU]:
State or Province Name (full name) [Some-State]:
Locality Name (eg, city) []:
Organization Name (eg, company) [Internet Widgits Pty Ltd]:
Organizational Unit Name (eg, section) []:
Common Name (e.g. server FQDN or YOUR name) []:
Email Address []:

// 成功后会出现 server.key 和 server.cert 两个文件
3.安装所需包
// 初始化
npm init
// 注意对应的node版本
npm install express
4.在nodeServer文件下创建 server.js
const app = require("express")()
const fs = require("fs")

// 私钥跟证书
const httpsOption = {
  key: fs.readFileSync("./server.key"),
  cert: fs.readFileSync("./server.cert"),
}

// 创建https
const https = require("https").Server(httpsOption, app)
// 端口
const port = 3000

// 定义根路由
app.get('/', (req, res) => {
  res.send("<h1>你好啊,https</h1>")
})

https.listen(port, () => {
  console.log(`服务启动成功!`)
  console.log(`https://localhost:${port}`)
})
5.运行
node ./server.js

// 出现 服务启动成功!  即可访问 https://localhost:3000

node运行vue项目

上面已经成功的起了node服务,可以定义接口模拟数据等
现在需要能访问一些静态文件

可以在当前文件夹下放入 dist 文件 或 引入vue项目并打包 访问dist (则无需复制文件到处放)

// 1. 需要引入
const express = require('express')
const path = require('path')
// 2.设置静态资源访问目录
app.use(express.static('dist'))
// 3.当任何路由未匹配到时,均返回index.html以支持前端路由管理
// 解决刷新就不能访问
app.get('*', function (req, res) {
  res.sendFile(path.join(__dirname, 'dist', 'index.html'));
});

或 

app.use(express.static('./vue/dist'))
app.get('*', function (req, res) {
  res.sendFile(path.join(__dirname, './vue/dist', 'index.html'));
});

注意:

当把vue项目打包的dist文件放进去访问时,页面可以出来,但静态资源报错,可以查看config配置文件
publicPath: process.env.NODE_ENV === "production" ? "/" : "/",
应该改为 ./

========================================

目录
在这里插入图片描述
整体代码

const app = require("express")()
const express = require('express')
const fs = require("fs")
const path = require('path')

// 私钥跟证书
const httpsOption = {
  key: fs.readFileSync("./server.key"),
  cert: fs.readFileSync("./server.cert"),
}

// 创建https
const https = require("https").Server(httpsOption, app)

// 端口
const port = 3000

// app.use(express.static('dist')) // 设置静态资源访问目录
app.use(express.static('./vue/dist')) // 设置静态资源访问目录

// 当任何路由未匹配到时,均返回index.html以支持前端路由管理
app.get('*', function (req, res) {
  res.sendFile(path.join(__dirname, './vue/dist', 'index.html'));
});

https.listen(port, () => {
  console.log(`服务启动成功!`)
  console.log(`https://localhost:${port}`)
})

使用express服务部署vue项目

…

Logo

北京人形旗下天工造物具身智能开源社区,聚焦具身天工与慧思开物两大平台

更多推荐