在腾讯云轻量应用服务器上配置 Node.js 服务用于小程序,是一个常见且实用的场景。以下是详细的配置步骤,帮助你从零开始搭建一个支持微信小程序后端的 Node.js 服务。
✅ 一、准备工作
-
购买并登录腾讯云轻量应用服务器
- 登录 腾讯云控制台
- 创建一台轻量应用服务器(建议选择 Ubuntu 20.04 / 22.04 或 CentOS 系统)
- 记下公网 IP 地址和登录密码/密钥
-
开放端口
- 在轻量服务器“防火墙”设置中,放行以下端口:
22:SSH 登录80:HTTP(可选,用于反向X_X)443:HTTPS(可选)3000或其他你计划使用的 Node.js 端口(如5000)
- 在轻量服务器“防火墙”设置中,放行以下端口:
✅ 二、连接服务器并安装 Node.js
使用 SSH 连接到你的服务器:
ssh root@你的公网IP
安装 Node.js(推荐使用 nvm)
# 安装 nvm(Node Version Manager)
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash
# 重新加载 shell 配置
source ~/.bashrc
# 安装最新长期支持版 Node.js(如 v18)
nvm install 18
# 设置默认使用
nvm use 18
nvm alias default 18
# 验证安装
node -v # 应输出 v18.x.x
npm -v
✅ 三、创建 Node.js 后端服务(示例)
1. 创建项目目录
mkdir /home/myapp && cd /home/myapp
npm init -y
npm install express cors body-parser
2. 创建 server.js
// server.js
const express = require('express');
const cors = require('cors');
const app = express();
const PORT = process.env.PORT || 3000;
app.use(cors());
app.use(express.json());
// 小程序测试接口
app.get('/api/hello', (req, res) => {
res.json({ message: 'Hello from Tencent Cloud Light Server!', timestamp: new Date() });
});
app.post('/api/data', (req, res) => {
const { name } = req.body;
res.json({ greeting: `Hello ${name}! Welcome to your mini-program backend.` });
});
app.listen(PORT, '0.0.0.0', () => {
console.log(`Server is running on http://0.0.0.0:${PORT}`);
});
注意:绑定
'0.0.0.0'才能通过公网访问,不能只用localhost。
✅ 四、启动服务(使用 PM2 守护进程)
防止 Node.js 服务在关闭终端后停止,建议使用 PM2。
npm install -g pm2
# 启动服务
pm2 start server.js --name "miniapp-backend"
# 设置开机自启
pm2 startup
pm2 save
查看服务状态:
pm2 status
pm2 logs # 查看日志
✅ 五、测试接口是否可用
在浏览器或 Postman 中访问:
http://你的服务器公网IP:3000/api/hello
如果返回 JSON 数据,说明服务已正常运行。
✅ 六、小程序前端调用示例(微信小程序)
在小程序的 page.js 中:
wx.request({
url: 'http://你的服务器IP:3000/api/hello',
method: 'GET',
success(res) {
console.log(res.data);
},
fail(err) {
console.error('请求失败:', err);
}
});
⚠️ 注意:
- 微信小程序要求 HTTPS 域名(正式上线时必须)。
- 开发阶段可在「开发设置」中添加不校验合法域名的选项(仅限调试)。
✅ 七、进阶建议(生产环境)
| 功能 | 推荐方案 |
|---|---|
| 域名绑定 | 购买域名并解析到服务器 IP |
| HTTPS | 使用 Nginx + 免费 SSL 证书(Let’s Encrypt) |
| 反向X_X | 用 Nginx X_X Node.js 服务(端口 80 → 3000) |
| 数据库 | 安装 MongoDB / MySQL / 或使用腾讯云数据库 |
示例:Nginx 反向X_X配置
server {
listen 80;
server_name yourdomain.com; # 替换为你的域名
location / {
proxy_pass http://127.0.0.1:3000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
然后申请 SSL 证书启用 HTTPS。
✅ 八、安全建议
- 关闭不必要的端口
- 修改 SSH 默认端口,禁用 root 密码登录
- 定期更新系统:
sudo apt update && sudo apt upgrade -y - 使用
.env文件管理敏感信息(如数据库密码)
总结
你现在已经在腾讯云轻量服务器上成功部署了一个可用于微信小程序的 Node.js 后端服务。关键步骤包括:
- 购买并配置轻量服务器
- 安装 Node.js 和 PM2
- 编写 Express 接口
- 网络访问测试
- 小程序调用接口
- (可选)配置域名 + HTTPS 提升安全性
如有需要,我可以提供完整的 GitHub 示例项目结构或自动部署脚本。欢迎继续提问!
CLOUD技术博