快速搭建Node.js服务指南

发布于:2025-08-01 ⋅ 阅读:(15) ⋅ 点赞:(0)

Node.js是构建高效、可扩展网络应用的理想选择。以下是几种快速搭建Node.js服务的方法。

方法一:使用Express(最流行框架)

1. 初始化项目

mkdir my-node-service
cd my-node-service
npm init -y

2. 安装Express

npm install express

3. 基础服务代码

创建app.jsindex.js文件:

const express = require('express')
const app = express()
const port = 3000

// 中间件
app.use(express.json())

// 路由
app.get('/', (req, res) => {
  res.send('Hello World!')
})

// 带参数的路由
app.get('/user/:id', (req, res) => {
  res.send(`User ID: ${req.params.id}`)
})

// POST请求示例
app.post('/data', (req, res) => {
  console.log(req.body)
  res.json({ received: true })
})

// 启动服务
app.listen(port, () => {
  console.log(`服务运行在 http://localhost:${port}`)
})

4. 运行服务

node app.js

方法二:使用Koa(更现代的框架)

1. 安装Koa

npm install koa @koa/router

2. 基础服务代码

const Koa = require('koa')
const Router = require('@koa/router')

const app = new Koa()
const router = new Router()

router.get('/', (ctx) => {
  ctx.body = 'Hello Koa!'
})

app.use(router.routes())
app.use(router.allowedMethods())

app.listen(3000, () => {
  console.log('服务运行在 http://localhost:3000')
})

方法三:使用Fastify(高性能框架)

1. 安装Fastify

npm install fastify

2. 基础服务代码

const fastify = require('fastify')({ logger: true })

fastify.get('/', async (request, reply) => {
  return { hello: 'world' }
})

const start = async () => {
  try {
    await fastify.listen({ port: 3000 })
  } catch (err) {
    fastify.log.error(err)
    process.exit(1)
  }
}
start()

数据库集成(以MongoDB为例)

1. 安装mongoose

npm install mongoose

2. 连接数据库

const mongoose = require('mongoose')

mongoose.connect('mongodb://localhost:27017/mydatabase')
  .then(() => console.log('MongoDB连接成功'))
  .catch(err => console.error('MongoDB连接失败', err))

3. 定义模型和路由

const User = mongoose.model('User', new mongoose.Schema({
  name: String,
  email: String
}))

app.get('/users', async (req, res) => {
  const users = await User.find()
  res.json(users)
})

app.post('/users', async (req, res) => {
  const user = new User(req.body)
  await user.save()
  res.status(201).send(user)
})

中间件使用示例

1. 常用中间件安装

npm install cors morgan helmet

2. 中间件配置

const cors = require('cors')
const morgan = require('morgan')
const helmet = require('helmet')

app.use(cors()) // 跨域支持
app.use(morgan('combined')) // 请求日志
app.use(helmet()) // 安全头设置

项目结构建议

my-node-service/
├── node_modules/
├── src/
│   ├── controllers/    # 控制器
│   ├── models/         # 数据模型
│   ├── routes/         # 路由定义
│   ├── middlewares/    # 自定义中间件
│   ├── utils/          # 工具函数
│   └── app.js          # 主应用文件
├── .env                # 环境变量
├── package.json
└── README.md

环境配置

1. 安装dotenv

npm install dotenv

2. 创建.env文件

PORT=3000
MONGODB_URI=mongodb://localhost:27017/mydatabase
JWT_SECRET=mysecretkey

3. 加载配置

require('dotenv').config()

const port = process.env.PORT || 3000
app.listen(port, () => {
  console.log(`服务运行在 ${port} 端口`)
})

错误处理

1. 添加错误处理中间件

// 最后添加
app.use((err, req, res, next) => {
  console.error(err.stack)
  res.status(500).send('出错了!')
})

2. 异步错误处理

const asyncHandler = fn => (req, res, next) => 
  Promise.resolve(fn(req, res, next)).catch(next)

app.get('/async', asyncHandler(async (req, res) => {
  const data = await someAsyncOperation()
  res.json(data)
}))

服务部署

1. 使用PM2进程管理

npm install pm2 -g
pm2 start app.js

2. 常用PM2命令

pm2 list         # 查看运行中的进程
pm2 stop app     # 停止应用
pm2 restart app  # 重启应用
pm2 logs         # 查看日志

进阶建议

  1. API文档:使用Swagger UI

    npm install swagger-ui-express swagger-jsdoc
    
  2. 验证:使用JWT

    npm install jsonwebtoken bcryptjs
    
  3. 测试:使用Jest

    npm install jest supertest --save-dev
    
  4. TypeScript支持

    npm install typescript @types/node @types/express --save-dev
    
  5. Docker化

    FROM node:16
    WORKDIR /app
    COPY package*.json ./
    RUN npm install
    COPY . .
    EXPOSE 3000
    CMD ["node", "app.js"]
    

选择适合你项目需求的框架和方法,Express适合大多数Web应用,Koa提供更现代的中间件机制,Fastify则专注于高性能。


网站公告

今日签到

点亮在社区的每一天
去签到