http.createServer 接收一个回调函数,每次请求触发一次。回调里 req 是请求对象,可以读取请求头、URL 与请求体;res 是响应对象,通过 setHeader、write 写入内容,最后必须调用 end() 返回响应——不调用 end 客户端请求就会一直挂起等待。
http 模块本身不提供路由、参数解析等高级能力,一切要自己写或交给 Express 等框架。它也可以作为客户端用 http.request 发起请求。生产环境很少裸用 http,但理解它对掌握上层框架的中间件机制、流式响应与 Keep-Alive 连接复用至关重要。
const http = require('http'); const server = http.createServer((req, res) => { if (req.url === '/') { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end('Hello Node'); } else { res.writeHead(404); res.end('Not Found'); } }); server.listen(3000, () => { console.log('服务运行在 3000 端口'); });