返回博客列表
BackendNode.jsExpressAPI

Node.js 后端开发实战:构建 RESTful API

WyperBlog2024-11-2014 分钟

Node.js 后端开发实战

使用 Node.js 和 Express.js 构建现代化的 RESTful API。

项目初始化

bash
mkdir my-api
cd my-api
npm init -y
npm install express typescript @types/express
npx tsc --init

基础服务器

typescript
import express from 'express'

const app = express()
const PORT = process.env.PORT || 3000

app.use(express.json())

app.get('/api/health', (req, res) => {
  res.json({ status: 'ok' })
})

app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`)
})

路由组织

typescript
// routes/users.ts
import { Router } from 'express'

const router = Router()

router.get('/', async (req, res) => {
  // 获取所有用户
  res.json({ users: [] })
})

router.post('/', async (req, res) => {
  // 创建用户
  res.status(201).json({ message: 'User created' })
})

export default router

中间件

typescript
// middleware/auth.ts
export function authMiddleware(req, res, next) {
  const token = req.headers.authorization
  
  if (!token) {
    return res.status(401).json({ error: 'Unauthorized' })
  }
  
  // 验证 token
  next()
}

错误处理

typescript
app.use((err, req, res, next) => {
  console.error(err.stack)
  res.status(500).json({ error: 'Internal server error' })
})

总结

Express.js 提供了简洁而强大的 API 开发体验。

觉得文章不错?点个赞吧

评论 (0)

还没有评论,来发表第一条评论吧!