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

成功!!完结

相关推荐
an317428 分钟前
弹窗数据流设计的两种高阶架构实践
前端·vue.js·架构
谢尔登23 分钟前
【React】 状态管理方案
前端·react.js·前端框架
用户9385156350740 分钟前
手把手教你实现一个 MCP 文件读取服务器:从协议到代码的深度解析
javascript·人工智能
用户21366100357242 分钟前
Vue商品详情与放大镜组件
前端·javascript
半个落月1 小时前
从Tapas小Demo理清localStorage、事件与this
前端·javascript
用户938515635071 小时前
RAG 实战:从零搭建语义搜索系统,彻底告别关键词匹配的尴尬
javascript·人工智能
李明卫杭州1 小时前
Vue2 中 v-model 处理不同数据结构的技巧
前端·javascript·vue.js
李明卫杭州1 小时前
使用 computed 处理 v-model 复杂数据结构
前端·javascript·vue.js
丨我是张先生丨1 小时前
日语单词 Web Page
前端·css·css3
禅思院3 小时前
AI对话前端从入门到崩溃:一个长对话引发的五层优化战争【引子】
前端·面试·架构