从零开始用react + tailwindcss + express + mongodb实现一个聊天程序(十四) 部署

修改server下 package.json

{

"name": "server",

"version": "1.0.0",

"description": "",

"main": "index.js",

"scripts": {

"dev": "nodemon src/index.js",

"start": "node src/index.js"

},

"type": "module",

"author": "",

"license": "ISC",

"dependencies": {

"bcryptjs": "^3.0.2",

"chat-app": "file:..",

"cloudinary": "^2.5.1",

"cookie-parser": "^1.4.7",

"cors": "^2.8.5",

"dotenv": "^16.4.7",

"express": "^4.21.2",

"jsonwebtoken": "^9.0.2",

"mongoose": "^8.10.1",

"socket.io": "^4.8.1"

},

"devDependencies": {

"nodemon": "^3.1.9"

}

}

在项目根目录下执行npm init 得到json文件 内容如下

javascript 复制代码
{
    "name": "chat-app",
    "version": "1.0.0",
    "description": "",
    "main": "index.js",
    "scripts": {
      "build": "npm install --prefix server && npm install --prefix web && npm run build --prefix web",
      "start": "npm run start --prefix server"
    },
    "keywords": [],
    "author": "",
    "license": "ISC"
  }

修改server下 index.js

import express from "express"

import authRoutes from './routes/auth.route.js'

import messageRoutes from './routes/message.route.js'

import dotenv from 'dotenv'

import {connectDB} from "./lib/db.js"

import bodyParser from 'body-parser'

import cookieParser from 'cookie-parser'

import cors from 'cors'

import path from "path";

import {app,server} from './lib/socket.js'

dotenv.config();

const PORT = process.env.PORT

const __dirname = path.resolve();

// 跨域配置

// app.options('*', cors()) // include before other routes

app.use(cors({

origin:'http://localhost:5173',

credentials: true

}))

// 解决req.body undefined问题

app.use(cookieParser())

app.use(bodyParser.json())

app.use(bodyParser.urlencoded({ extended: true }))

// 实现signup 注册接口 认证

app.use('/api/auth', authRoutes)

// 消息接口

app.use('/api/messages', messageRoutes)

if (process.env.NODE_ENV === "production") {

app.use(express.static(path.join(__dirname, "../web/dist")));

app.get("*", (req, res) => {

res.sendFile(path.join(__dirname, "../web", "dist", "index.html"));

});

}

server.listen(PORT, () => {

console.log(process.env.NODE_ENV)

console.log("server is running on PORT:" + PORT);

connectDB();

});

把代码上传到服务器 在服务器中安装node 和 pm2

在项目根目录下

执行npm run build 在执行pm2 start --name XXX npm -- start

成功!!完结

相关推荐
Thomas游戏开发6 分钟前
Unity3D 文件夹注释工具
前端框架·unity3d·游戏开发
老坛0018 分钟前
2025决策延迟的椭圆算子分析:锐减协同工具的谱间隙优化
前端
老坛0019 分钟前
从记录到预测:2025新一代预算工具如何通过AI实现前瞻性资金管理
前端
今禾11 分钟前
" 当Base64遇上Blob,图像转换不再神秘,让你的网页瞬间变身魔法画布! "
前端·数据可视化
华科云商xiao徐16 分钟前
高性能小型爬虫语言与代码示例
前端·爬虫
十盒半价17 分钟前
深入理解 React useEffect:从基础到实战的全攻略
前端·react.js·trae
攀登的牵牛花17 分钟前
Electron+Vue+Python全栈项目打包实战指南
前端·electron·全栈
iccb101318 分钟前
我是如何实现在线客服系统的极致稳定性与安全性的
前端·javascript·后端
一大树19 分钟前
Vue3祖孙组件通信方法总结
前端·vue.js
不要进入那温驯的良夜20 分钟前
跨平台UI自动化-Appium
前端