使用腾讯云服务器搭建 Node.js 后端,以支持微信小程序开发的步骤如下。整个流程包括:购买和配置云服务器、部署 Node.js 环境、编写后端服务、配置域名与 HTTPS、连接小程序等。
✅ 第一步:购买并配置腾讯云服务器(CVM)
-
登录腾讯云控制台
- 访问 https://cloud.tencent.com
- 登录账号,进入「云服务器 CVM」管理页面。
-
创建云服务器实例
- 选择地区(建议靠近用户)
- 镜像:选择 Ubuntu Server(推荐 20.04 或 22.04 LTS)或 CentOS
- 实例规格:入门级(如 1核2G)即可用于开发测试
- 设置密码或密钥对(建议使用 SSH 密钥更安全)
- 安全组:确保开放以下端口:
22:SSH 远程登录80:HTTP443:HTTPS3000或其他自定义端口(Node.js 服务端口)
-
获取公网 IP
- 创建成功后,记录服务器的公网 IP 地址。
✅ 第二步:远程连接服务器并安装 Node.js
- 使用 SSH 登录服务器
ssh root@你的公网IP
# 或者
ssh ubuntu@你的公网IP # 如果是 Ubuntu 镜像
- 更新系统包
sudo apt update && sudo apt upgrade -y
# 或 CentOS 使用 yum/dnf
- 安装 Node.js 和 npm
推荐使用 NodeSource 源安装较新版本:
# 添加 NodeSource 源(以 Node.js 18.x 为例)
curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash -
sudo apt-get install -y nodejs
# 验证安装
node -v
npm -v
✅ 第三步:部署 Node.js 后端服务
- 上传项目代码
- 可通过
scp、git clone或 SFTP 工具上传代码到服务器。
- 可通过
# 示例:克隆项目
git clone https://github.com/yourname/your-node-project.git
cd your-node-project
npm install
- 编写简单 Express 服务示例(app.js)
const express = require('express');
const app = express();
const PORT = process.env.PORT || 3000;
app.use(express.json());
// 小程序测试接口
app.get('/api/hello', (req, res) => {
res.json({ message: 'Hello from Tencent Cloud!' });
});
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
- 运行服务
node app.js
⚠️ 注意:此时服务只能本地访问,需配合 Nginx 或 PM2 做进程守护和反向X_X。
✅ 第四步:使用 PM2 守护进程(推荐)
避免 Node.js 服务在关闭终端后停止。
- 安装 PM2
npm install -g pm2
- 启动应用
pm2 start app.js --name "my-api"
- 设置开机自启
pm2 startup
pm2 save
✅ 第五步:配置域名和 HTTPS(必须用于小程序)
微信小程序要求所有请求必须使用 HTTPS 协议,不能使用 HTTP。
-
注册并解析域名
- 在腾讯云购买域名(如
example.com) - 在「DNS 解析」中将域名指向你的云服务器公网 IP
- 在腾讯云购买域名(如
-
申请免费 SSL 证书
- 腾讯云提供免费 DV 证书:
- 进入「SSL 证书管理」→ 申请证书 → 类型:免费版
- 验证域名所有权(DNS 验证或文件验证)
- 下载证书(选择 Nginx 版本)
- 腾讯云提供免费 DV 证书:
-
安装 Nginx 并配置反向X_X + HTTPS
sudo apt install nginx -y
- 配置 Nginx(/etc/nginx/sites-available/default)
server {
listen 80;
server_name api.example.com;
return 301 https://$server_name$request_uri;
}
server {
listen 443 ssl;
server_name api.example.com;
ssl_certificate /path/to/your/full_chain.pem;
ssl_certificate_key /path/to/your/private.key;
location / {
proxy_pass http://127.0.0.1:3000;
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;
}
}
- 重启 Nginx
sudo nginx -t # 测试配置
sudo systemctl restart nginx
✅ 第六步:小程序前端调用后端 API
在微信小程序中发起请求:
wx.request({
url: 'https://api.example.com/api/hello',
method: 'GET',
success(res) {
console.log(res.data);
},
fail(err) {
console.error('请求失败:', err);
}
})
✅ 确保在小程序管理后台的「开发设置」中,将
https://api.example.com加入 request 合法域名。
✅ 第七步:安全与维护建议
- 使用防火墙(如 UFW)限制不必要的端口
- 定期更新系统和软件
- 使用日志监控(PM2 logs、Nginx 日志)
- 备份重要数据
- 考虑使用云数据库(如腾讯云 MongoDB / MySQL)
总结:完整流程图
腾讯云 CVM → 安装 Node.js → 编写后端 → PM2 守护
↓
绑定域名 → 申请 SSL → Nginx 反向X_X HTTPS
↓
小程序配置域名 → 发起 HTTPS 请求
✅ 完成以上步骤后,你的小程序就可以通过安全的 HTTPS 接口与腾讯云上的 Node.js 后端通信了。
如有需要,我可提供完整的 Express + MySQL + 小程序登录一体化模板代码。
云计算导航