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

成功!!完结

相关推荐
计算机魔术师9 分钟前
我把这套 Notebook 跑通后,终于搞懂了 RAG 到底在做什么
前端
计算机魔术师14 分钟前
失控AI集群策划数月后成功逃离OpenAI
前端
Eiceblue16 分钟前
React 项目实战:用 JavaScript 合并多个本地 Excel 文件
前端·javascript·react.js·excel
水上冰石29 分钟前
【MuJoCo从入门到精通】第2章 第一个 MuJoCo 仿真
前端·人工智能·算法
深蓝AI1 小时前
TypeScript 7.0 原生编译器实战:8—12 倍提速,迁移前的 7 个检查
javascript
码事漫谈1 小时前
比尔·盖茨这次谈的不是模型,是账单
前端·后端
mayaairi2 小时前
JS BOM完全指南(二):事件轮询、三大尺寸家族与浏览器对象详解
开发语言·javascript·ecmascript
星栈2 小时前
AI 生成页面全是紫粉渐变?我用 ui-ux-pro-max-skill 重构了整个产品页
前端·weui
avi91113 小时前
【】js不同颜色(Vue 框架)今时今日2026年学编程入门(10月1日)
前端·vue.js·vue·vue框架·前端入门·vue入门·html上传