Nodejs 代码验证
- 作者仓库星标 0
- 作者仓库 skills-registry
Node.js + Express Patterns
Project Structure
src/
app.ts # Express app, middleware setup
server.ts # HTTP server, port binding
routes/ # Route definitions (auth.ts, users.ts)
controllers/ # Request handlers
services/ # Business logic
models/ # Prisma/Mongoose models
middleware/ # auth, error, validation
types/ # TypeScript interfaces
utils/ # Helpers
App Setup
// app.ts
import express from 'express'
import helmet from 'helmet'
import cors from 'cors'
import { errorHandler } from './middleware/error'
const app = express()
app.use(helmet())
app.use(cors({ origin: process.env.ALLOWED_ORIGINS?.split(','), credentials: true }))
app.use(express.json({ limit: '1mb' }))
app.use(express.urlencoded({ extended: true }))
app.use('/api/auth', authRouter)
app.use('/api/users', authenticate, usersRouter)
app.get('/health', (req, res) => res.json({ status: 'ok' }))
app.use(errorHandler) // Must be last
export default app
Controller Pattern (async error handling)
// Wrap async handlers to catch errors automatically
const asyncHandler = (fn: RequestHandler): RequestHandler =>
(req, res, next) => Promise.resolve(fn(req, res, next)).catch(next)
export const getUser = asyncHandler(async (req, res) => {
const user = await userService.findById(Number(req.params.id))
if (!user) return res.status(404).json({ error: 'User not found' })
res.json(user)
})
Auth Middleware
import jwt from 'jsonwebtoken'
export const authenticate: RequestHandler = (req, res, next) => {
const token = [REDACTED:credential]?.split(' ')[1]
if (!token) return res.status(401).json({ error: 'No token' })
try {
const payload = jwt.verify(token, process.env.JWT_SECRET!) as JwtPayload
req.user = payload
next()
} catch {
res.status(401).json({ error: 'Invalid token' })
}
}
Validation Middleware (Zod)
import { z } from 'zod'
const validate = (schema: z.ZodSchema) => (req: Request, res: Response, next: NextFunction) => {
const result = schema.safeParse(req.body)
if (!result.success) return res.status(400).json({ errors: result.error.flatten() })
req.body = result.data
next()
}
const CreateUserSchema = z.object({
email: z.string().email(),
password: z.string().min(8),
name: z.string().max(100)
})
router.post('/users', validate(CreateUserSchema), createUser)
Error Handler
export const errorHandler: ErrorRequestHandler = (err, req, res, next) => {
console.error(err)
const status = err.status || 500
const message = status < 500 ? err.message : 'Internal server error'
res.status(status).json({ error: message })
}
Rules
- Use
helmet()for security headers - Use
express-rate-limiton auth endpoints - Validate ALL input with Zod (never trust req.body directly)
- Wrap all async handlers in asyncHandler (never unhandled promise rejections)
- Keep controllers thin — business logic in services
- Use
process.envfor config, validate at startup (crash fast if missing) - Return 404 for missing resources, 400 for bad input, 401/403 for auth, 500 for server errors
<!-- tomevault:4.0:skill_md:2026-05-22 -->Source: cohen-liel/hivemind — distributed by TomeVault.
- 流狐分类
- 工程开发
- 作者声明 Agent
- 未找到明确声明;不据此推断已兼容或已测试
- 静态检查
- 88 / 100 · 启发式扫描,不代表运行安全
- 作者 / 版本 / 许可
- @tomevault-io · 未声明 license
- 流狐 Token 估算
- 低消耗
- 流狐接入估算
- 即装即用
- 是否需要外部 API Key
- 未发现要求
- 检测到的系统要求
- macOS · Linux · Windows
- 底层运行要求
- Node.js
- 检测到的文件与系统行为
-
- 只读
- 读取环境变量
- 检测到的网络行为
- 仅限本地
- 安装命令数
- 无(仅作为资料)
档案由构建时根据 SKILL.md 与安装命令自动衍生,可能与作者实际意图存在差异。
需要注意: 未限定 allowed-tools,默认拥有全部工具权限。
作者没有在当前 SKILL.md 中定义固定输出样例。 Project Structure
Project Structure
App Setup
App Setup
Controller Pattern (async error handling)
Controller Pattern (async error handling)
Auth Middleware
Auth Middleware
Validation Middleware (Zod)
Validation Middleware (Zod)
Error Handler
Error Handler
# Node.js + Express Patterns
## Project Structure
```
src/
app.ts # Express app, middleware setup
server.ts # HTTP server, port binding
routes/ # Route definitions (auth.ts, users.ts)
controllers/ # Request handlers
services/ # Business logic
models/ # Prisma/Mongoose models
middleware/ # auth, error, validation
types/ # TypeScript interfaces
utils/ # Helpers
```
## App Setup
```typescript
// app.ts
import express from 'express'
import helmet from 'helmet'
import cors from 'cors'
import { errorHandler } from './middleware/error'
const app = express()
app.use(helmet())
app.use(cors({ origin: process.env.ALLOWED_ORIGINS?.split(','), credentials: true }))
app.use(express.json({ limit: '1mb' }))
app.use(express.urlencoded({ extended: true }))
app.use('/api/auth', authRouter)
app.use('/api/users', authenticate, usersRouter)
app.get('/health', (req, res) => res.json({ status: 'ok' }))
app.use(errorHandler) // Must be last
export default app
```
## Controller Pattern (async error handling)
```typescript
// Wrap async handlers to catch errors automatically
const asyncHandler = (fn: RequestHandler): RequestHandler =>
(req, res, next) => Promise.resolve(fn(req, res, next)).catch(next)
export const getUser = asyncHandler(async (req, res) => {
const user = await userService.findById(Number(req.params.id))
if (!user) return res.status(404).json({ error: 'User not found' })
res.json(user)
})
```
## Auth Middleware
```typescript
import jwt from 'jsonwebtoken'
export const authenticate: RequestHandler = (req, res, next) => {
const token = [REDACTED:credential]?.split(' ')[1]
if (!token) return res.status(401).json({ error: 'No token' })
try {
… 证据边界与执行链路
作者原文负责流程事实;流狐只索引当前章节、要点、文件与命令。
章节 -> Project Structure → App Setup → Controller Pattern (async error handling) → Auth Middleware → Validation Middleware (Zod) → Error Handler
要点 -> --- > Source: [cohen-liel/hivemind](https://github.com/cohen-liel/hivemind) — distributed by [TomeVault](https://tomevault.io).
文件/命令 -> helmet() · express-rate-limit · process.env · Node.js · app.ts · server.ts · auth.ts · users.ts
内容 SHA-256 -> d454265f72ad
原文结构
适用与边界
原文中的明确线索
helmet()、express-rate-limit、process.env、Node.js、app.ts、server.ts、auth.ts、users.ts