← 中文资源

简体中文版本

node:http 不用框架返回 JSON

node:http 的 createServer 不引任何框架就能回 JSON:listen(0) 让系统分配空闲端口,writeHead 设状态与响应头,close 释放句柄后进程自然退出。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

listening: true
closed cleanly

实现说明

node:http 提供 createServer——内建表面,不涉及任何包。 演示用的数据放在这几个模块级绑定中:server。

使用要点

  • 无需安装:node:http 随 Node.js 本体提供。
  • 每一步打印都带着自己的标签:listening:、closed cleanly。

常见问题

导入的模块是 npm 包吗?

不需要——node:http 内置于 Node.js。node: 前缀就代表核心模块,项目里无需添加任何东西。

核心语句

res.end(JSON.stringify({ status: 'ok', path: req.url }));
server.listen(0, '127.0.0.1', () => {
  const { port } = server.address();
  console.log('listening:', port > 0);
  // Closing frees the handle so the process can exit on its own
  server.close(() => console.log('closed cleanly'));
});

代码示例

import { createServer } from 'node:http';

const server = createServer((req, res) => {
  // writeHead sets status and headers first; res.end writes the body
  res.writeHead(200, { 'content-type': 'application/json' });
  res.end(JSON.stringify({ status: 'ok', path: req.url }));
});

// Port 0 asks the OS for a free ephemeral port instead of a fixed one
server.listen(0, '127.0.0.1', () => {
  const { port } = server.address();
  console.log('listening:', port > 0);
  // Closing frees the handle so the process can exit on its own
  server.close(() => console.log('closed cleanly'));
});