req.method 区分 GET/POST,re"> req.method 区分 GET/POST,re"> req.method 区分 GET/POST,re">
Node.js 词条目录
前端Wiki/Node.js/深入/http 模块

请求与响应处理

处理请求主要是拆解 req:req.method 区分 GET/POST,req.url 含路径与查询串,请求头在 req.headers(全小写键名)。请求体需要手动收集——POST 数据以“流”的形式分块到达,要监听 data/end 事件拼接。

返回 JSON 是最常见的需求:Content-Type 写 application/json,res.end(JSON.stringify(data))。注意所有响应头必须在 writeHead 一次性写好后再 end。

  • GET 请求没有请求体,参数全在 req.url 的查询串里
  • POST 请求体靠 req.on("data") 分块收集、on("end") 拼接完成
  • 返回 JSON:头写 application/json,体 JSON.stringify
JS
const http = require('http');

http.createServer((req, res) => {
  if (req.method === 'POST' && req.url === '/api/user') {
    let body = '';
    // 请求体是流:分块到达,要自己拼
    req.on('data', chunk => body += chunk);
    req.on('end', () => {
      const user = JSON.parse(body || '{}');
      const resp = { ok: true, echo: user };
      res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
      res.end(JSON.stringify(resp));
    });
    return;
  }

  res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' });
  res.end('404 接口不存在');
}).listen(3000, () => console.log('跑在 3000'));

// 测试:curl -X POST localhost:3000/api/user -d '{"name":"小明"}' 
本节要点GET 参数在 url,POST 请求体靠 data/end 流式拼接;返回 JSON 只需正确的头 + JSON.stringify。