在轻量服务器上搭建微信小程序的 Node.js 后端是一个常见且实用的需求。以下是详细的步骤指南,帮助你从零开始部署一个支持微信小程序的 Node.js 服务。
✅ 一、准备工作
1. 购买并登录轻量服务器
- 推荐使用:腾讯云轻量应用服务器(Lighthouse)、阿里云轻量服务器等。
- 系统建议选择:Ubuntu 20.04 / 22.04 LTS(稳定、社区支持好)。
- 开放端口:确保防火墙开放
80(HTTP)、443(HTTPS)、3000(开发调试)等端口。
2. 连接服务器
使用 SSH 登录:
ssh root@你的服务器IP
✅ 二、安装 Node.js 和 npm
推荐使用 nvm(Node Version Manager)来管理 Node.js 版本。
# 安装 nvm
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash
# 重新加载配置
source ~/.bashrc
# 安装最新 LTS 版本的 Node.js(如 v18.x)
nvm install --lts
# 验证安装
node -v
npm -v
✅ 三、创建 Node.js 项目
# 创建项目目录
mkdir wechat-backend && cd wechat-backend
# 初始化项目
npm init -y
# 安装 Express 框架(或其他框架如 Koa)
npm install express cors dotenv
✅ 四、编写简单的后端 API
创建 app.js:
const express = require('express');
const cors = require('cors');
require('dotenv').config();
const app = express();
const PORT = process.env.PORT || 3000;
// 允许跨域(小程序需要)
app.use(cors());
app.use(express.json());
// 示例接口:获取用户信息
app.get('/api/user', (req, res) => {
res.json({ code: 0, data: { name: '张三', id: 1 } });
});
// 微信登录示例接口(后续可对接 wx.login)
app.post('/api/login', async (req, res) => {
const { code } = req.body; // 小程序传来的临时登录码
if (!code) {
return res.status(400).json({ error: '缺少 code' });
}
// TODO: 调用微信接口换取 openid 和 session_key
// https://api.weixin.qq.com/sns/jscode2session
res.json({ code: 0, msg: '登录成功', openid: 'mock_openid' });
});
app.listen(PORT, '0.0.0.0', () => {
console.log(`Server is running on http://0.0.0.0:${PORT}`);
});
✅ 五、后台运行服务(使用 PM2)
防止进程退出,使用 PM2 守护进程。
# 全局安装 PM2
npm install -g pm2
# 启动应用
pm2 start app.js --name "wechat-api"
# 设置开机自启
pm2 startup
pm2 save
常用命令:
pm2 status
pm2 logs
pm2 restart wechat-api
✅ 六、配置反向X_X(Nginx,推荐用于生产)
1. 安装 Nginx
sudo apt update
sudo apt install nginx -y
2. 配置站点(替换默认配置)
编辑 /etc/nginx/sites-available/default:
server {
listen 80;
server_name your-domain.com; # 或服务器IP
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;
proxy_cache_bypass $http_upgrade;
}
}
3. 重启 Nginx
sudo nginx -t # 测试配置
sudo systemctl reload nginx
✅ 七、域名与 HTTPS(可选但推荐)
1. 绑定域名
- 在域名服务商处将域名 A 记录指向服务器 IP。
2. 使用 Certbot 配置免费 HTTPS
sudo apt install certbot python3-certbot-nginx -y
sudo certbot --nginx -d your-domain.com
自动配置 SSL 证书,并启用 HTTPS。
✅ 八、小程序前端调用示例
在微信小程序中请求你的接口:
wx.request({
url: 'https://your-domain.com/api/user',
method: 'GET',
success(res) {
console.log(res.data);
}
})
⚠️ 注意:必须使用
https协议,且域名需在小程序管理后台「开发管理」→「开发设置」→「服务器域名」中配置。
✅ 九、安全建议
- 不要暴露敏感信息:如数据库密码、AppSecret 等,使用
.env文件管理。 - 开启日志监控:PM2 + 日志文件或 ELK。
- 定期更新系统和依赖:
npm audit检查漏洞。 - 限制 API 访问频率:防刷。
✅ 十、后续扩展
- 接入 MySQL/MongoDB 数据库
- 使用 JWT 实现用户鉴权
- 集成微信支付、消息推送等能力
- 使用 Docker 容器化部署
? 总结
| 步骤 | 内容 |
|---|---|
| 1 | 购买并连接轻量服务器 |
| 2 | 安装 Node.js 和 PM2 |
| 3 | 编写 Express 后端接口 |
| 4 | 使用 PM2 启动服务 |
| 5 | 配置 Nginx 反向X_X |
| 6 | 添加域名和 HTTPS |
| 7 | 小程序调用接口 |
如果你希望我提供完整的 GitHub 示例项目结构或一键部署脚本,也可以告诉我,我可以为你生成。
祝你顺利上线!?
CDNK博客