Skip to content

HTTP

Node.js 提供低层 node:http API。业务服务通常由框架封装;理解原生 API 有助于掌握请求、响应、流和连接生命周期。

服务端

js
import { createServer } from 'node:http'

const server = createServer((request, response) => {
  if (request.url === '/health') {
    response.writeHead(200, { 'content-type': 'application/json; charset=utf-8' })
    response.end(JSON.stringify({ ok: true }))
    return
  }

  response.writeHead(404)
  response.end()
})

server.listen(3000, '127.0.0.1')

IncomingMessage 是可读流,ServerResponse 是可写流。读取请求体必须限制大小、处理流错误并在客户端断开时停止后续工作。

客户端

新项目优先使用 Node.js 内置的 fetch

js
const controller = new AbortController()
const timeout = setTimeout(() => controller.abort(), 5_000)

try {
  const response = await fetch('https://api.example.com/users', {
    signal: controller.signal,
  })

  if (!response.ok) throw new Error(`HTTP ${response.status}`)
  const users = await response.json()
} finally {
  clearTimeout(timeout)
}

fetch 仅在网络层失败时 reject;404500 仍会得到正常的 Response,必须检查 response.ok。生产请求应设置超时、限制重试范围,并在适用时复用连接。

服务端基本约束

  • 显式设置状态码和 Content-Type;JSON 使用 UTF-8。
  • 不信任 Host、转发头和请求体;反向代理场景需明确可信代理范围。
  • 设置请求、响应和 keep-alive 超时,防止慢速连接耗尽资源。
  • 服务关闭时停止接收新连接,并等待或在超时后关闭存量连接。

基于 MIT 许可发布