奋斗
努力

微信小程序连接腾讯云轻量服务器Node.js环境如何搭建?

云计算

在微信小程序中连接腾讯云轻量应用服务器(Lighthouse)并搭建 Node.js 后端环境,可以按照以下步骤进行操作。本文将详细介绍从服务器准备、Node.js 环境搭建到部署 API 服务,并让微信小程序安全调用的全过程。


✅ 一、准备工作

  1. 购买腾讯云轻量应用服务器(Lighthouse)

    • 登录 腾讯云官网
    • 搜索「轻量应用服务器」并购买一台(推荐选择 Ubuntu 或 CentOS 系统)
    • 记下公网 IP 地址和登录密码/密钥
  2. 域名备案(可选但建议)

    • 如果你希望使用自定义域名(如 api.yourdomain.com),需要完成 ICP 备案
    • 若仅测试,可直接使用公网 IP + 端口访问(但微信小程序要求 HTTPS)
  3. 申请 SSL 证书(必须)

    • 微信小程序要求所有网络请求必须通过 HTTPS 协议
    • 可免费申请腾讯云提供的 DV 域名型 SSL 证书(需绑定已备案域名)
    • 推荐使用 Let’s Encrypt 配合 Nginx 自动签发(如使用 Certbot)

✅ 二、连接服务器并安装 Node.js

1. 使用 SSH 连接服务器(以 Ubuntu 为例)

ssh root@你的公网IP
# 输入密码或使用私钥登录

2. 更新系统包

sudo apt update && sudo apt upgrade -y

3. 安装 Node.js(推荐使用 nvm)

# 安装 nvm
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash

# 重新加载 shell 配置
source ~/.bashrc

# 安装最新 LTS 版本的 Node.js
nvm install --lts
# 或指定版本:nvm install 18

# 验证安装
node -v
npm -v

✅ 三、创建简单的 Node.js 服务(Express 示例)

1. 创建项目目录

mkdir /opt/my-api
cd /opt/my-api
npm init -y
npm install express cors dotenv

2. 创建 server.js

// server.js
const express = require('express');
const cors = require('cors');
const app = express();

app.use(cors()); // 允许跨域(开发阶段)
app.use(express.json());

// 测试接口
app.get('/api/hello', (req, res) => {
  res.json({ message: 'Hello from Tencent Cloud Lighthouse!' });
});

// 微信小程序可调用此接口
app.post('/api/user', (req, res) => {
  const { name } = req.body;
  res.json({ code: 0, data: { id: 1, name: `Hello ${name}` } });
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, '0.0.0.0', () => {
  console.log(`Server is running on http://0.0.0.0:${PORT}`);
});

注意:监听 0.0.0.0 才能被网络访问

3. 启动服务(临时)

node server.js

✅ 四、配置反向X_X与 HTTPS(Nginx + SSL)

1. 安装 Nginx

sudo apt install nginx -y

2. 配置站点(假设域名为 api.example.com

编辑配置文件:

sudo nano /etc/nginx/sites-available/default

写入如下内容(根据实际情况修改域名和证书路径):

server {
    listen 80;
    server_name api.example.com;

    # 强制跳转 HTTPS
    return 301 https://$server_name$request_uri;
}

server {
    listen 443 ssl;
    server_name api.example.com;

    ssl_certificate /etc/nginx/ssl/fullchain.pem;     # 证书路径
    ssl_certificate_key /etc/nginx/ssl/privkey.pem;   # 私钥路径

    location / {
        proxy_pass http://127.0.0.1:3000;  # 转发到本地 Node.js 服务
        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;
    }
}

3. 放行防火墙端口

sudo ufw allow 'Nginx Full'
sudo ufw enable

4. 启动 Nginx

sudo systemctl start nginx
sudo systemctl enable nginx

5. 获取并配置 SSL 证书(以 Let’s Encrypt 为例)

# 安装 Certbot
sudo apt install certbot python3-certbot-nginx -y

# 获取证书(确保域名已解析到服务器 IP)
sudo certbot --nginx -d api.example.com

Certbot 会自动修改 Nginx 配置并设置自动续期。


✅ 五、使用 PM2 管理 Node.js 应用(生产环境推荐)

npm install -g pm2
pm2 start server.js --name "my-api"
pm2 startup
pm2 save

现在你的服务会在后台运行并开机自启。


✅ 六、微信小程序调用后端 API

在微信小程序中发起请求:

// pages/index/index.js
Page({
  onLoad() {
    wx.request({
      url: 'https://api.example.com/api/hello',
      method: 'GET',
      success(res) {
        console.log(res.data); // 输出:{ message: "Hello from Tencent Cloud..." }
      },
      fail(err) {
        console.error('请求失败:', err);
      }
    });
  }
});

⚠️ 注意事项:

  • 域名必须在微信公众平台 「开发管理」→「服务器域名」 中配置 request 合法域名
  • 必须是 HTTPS,不能是 IP + 端口(除非企业小程序特殊权限)
  • 不支持 HTTP 协议

✅ 七、常见问题排查

问题 解决方案
小程序提示“request:fail” 检查域名是否已添加到合法域名列表
Nginx 无法访问 检查安全组是否开放 80/443 端口
Node.js 服务无法网络访问 检查是否监听 0.0.0.0 而非 localhost
SSL 证书无效 使用正规 CA 证书(Let’s Encrypt 或腾讯云免费证书)

✅ 总结流程图

微信小程序
    ↓ (HTTPS)
腾讯云 DNS 域名解析 → 轻量服务器公网 IP
    ↓
Nginx (443 端口,SSL 解析)
    ↓ (反向X_X)
Node.js (运行在 3000 端口)

📌 补充建议

  • 使用 dotenv 管理环境变量(数据库、密钥等)
  • 添加日志记录(如 Winston)
  • 使用 MongoDB/MySQL 存储数据(可搭配腾讯云数据库)
  • 考虑使用 Serverless(如云函数 SCF)替代传统服务器更省成本

如果你提供具体需求(如用户登录、上传文件等),我可以进一步给出完整代码示例。

祝你部署顺利!🚀

未经允许不得转载:云服务器 » 微信小程序连接腾讯云轻量服务器Node.js环境如何搭建?