从零开始用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

成功!!完结

相关推荐
前端不太难6 小时前
从 Navigation State 反推架构腐化
前端·架构·react
前端程序猿之路6 小时前
Next.js 入门指南 - 从 Vue 角度的理解
前端·vue.js·语言模型·ai编程·入门·next.js·deepseek
大布布将军6 小时前
⚡️ 深入数据之海:SQL 基础与 ORM 的应用
前端·数据库·经验分享·sql·程序人生·面试·改行学it
川贝枇杷膏cbppg7 小时前
Redis 的 RDB 持久化
前端·redis·bootstrap
D_C_tyu7 小时前
Vue3 + Element Plus | el-table 表格获取排序后的数据
javascript·vue.js·elementui
JIngJaneIL7 小时前
基于java+ vue农产投入线上管理系统(源码+数据库+文档)
java·开发语言·前端·数据库·vue.js·spring boot
天外天-亮7 小时前
v-if、v-show、display: none、visibility: hidden区别
前端·javascript·html
jump_jump7 小时前
手写一个 Askama 模板压缩工具
前端·性能优化·rust
be or not to be8 小时前
HTML入门系列:从图片到表单,再到音视频的完整实践
前端·html·音视频
90后的晨仔8 小时前
在macOS上无缝整合:为Claude Code配置魔搭社区免费API完全指南
前端