🚀 总流程(一次搞清楚)
1. 创建 Vue 前端项目
2. 创建 Node.js 后端 API
3. 前后端本地联调
4. 打包前端(生成 dist)
5. 部署后端(PM2)
6. 部署前端(Nginx)
7. 使用 Nginx 做反向代理
8. 配置 HTTPS(可选)你可以完全照着下面做。
🟦 第一部分:创建 Vue 前端项目
✔ 1. 创建项目
npm create vite@latest vue-app
cd vue-app
npm install
npm run dev此时你的前端在:
✔ 添加一个测试 API 调用
src/App.vue:
onMounted(async () => {
const res = await fetch('/api/hello')
const data = await res.json()
console.log(data)
})🟩 第二部分:创建 Node 后端项目
✔ 1. 创建目录
mkdir node-api
cd node-api
npm init -y
npm install express cors✔ 2. 创建 app.js
const express = require('express')
const app = express()
app.get('/hello', (req, res) => {
res.json({ msg: "Hello from Node API!" })
})
app.listen(3000, () => {
console.log("API running on 3000")
})运行:
node app.js访问:
🟧 第三部分:前后端本地联调(Vite 代理)
编辑 vite.config.js:
server: {
proxy: {
'/api': {
target: 'http://localhost:3000',
changeOrigin: true,
rewrite: (path) => path.replace(/^/api/, '')
}
}
}现在访问 Vue 页面的时候,它能从 Node 获取数据。
🟥 第四部分:打包前端(生产环境)
运行:
npm run build会生成:
dist/
index.html
assets/这是生产环境前端资源,Nginx 会使用它。
🟦 第五部分:部署后端(PM2)
在服务器上安装:
npm install pm2 -g启动你的 Node:
pm2 start app.js --name node-api常用命令:
pm2 restart node-api
pm2 logs node-api
pm2 stop node-api
pm2 save
pm2 startupNode 后端现在稳定运行在 3000 端口。
🟩 第六部分:安装 Nginx(Win/Linux 都可以)
Windows Server
下载 Nginx:
- 官方 ZIP
- 解压到
C:nginx - 运行:
nginx.exe
Linux
sudo apt install nginx检查:
nginx -v🟧 第七部分:Nginx 配置前端 + 后端反向代理
🔥 这是最核心的配置(直接可用)
编辑:
Linux
/etc/nginx/sites-available/defaultWindows
nginx/conf/nginx.conf写入:
server {
listen 80;
server_name example.com;
# 前端
location / {
root D:/vue-app/dist;
try_files $uri $uri/ /index.html;
}
# 后端 API 反向代理
location /api/ {
proxy_pass http://127.0.0.1:3000/;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}测试配置:
nginx -t重启:
nginx -s reload🟫 效果验证(上线成功标准)
打开:
前端:
http://your-domain.com后端:
http://your-domain.com/api/hello如果你能看到 Node API 的输出,说明反向代理成功。
🟪 第八部分:配置 HTTPS(推荐)
使用免费的 Let’s Encrypt。
Linux:
sudo apt install certbot python3-certbot-nginx
sudo certbot --nginxWindows Server(推荐 Win-ACME):
wacs.exeNginx 生成的 HTTPS 配置会像:
listen 443 ssl;
ssl_certificate /path/fullchain.pem;
ssl_certificate_key /path/privkey.pem;