在 Node.js 中,你可以使用内置的 http 模块来处理 HTTP 请求。下面分别是处理 GET 和 POST 请求的简单例子:

处理 GET 请求
const http = require('http');
const url = require('url');

const server = http.createServer((req, res) => {
  // 解析请求的 URL
  const parsedUrl = url.parse(req.url, true);

  // 获取路径和查询参数
  const path = parsedUrl.pathname;
  const query = parsedUrl.query;

  // 处理不同的路径
  if (path === '/hello') {
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.end('Hello, World!');
  } else {
    res.writeHead(404, { 'Content-Type': 'text/plain' });
    res.end('Not Found');
  }
});

// 监听端口
const PORT = 3000;
server.listen(PORT, () => {
  console.log(`Server listening on port ${PORT}`);
});

处理 POST 请求
const http = require('http');
const querystring = require('querystring');

const server = http.createServer((req, res) => {
  // 接收 POST 数据
  let data = '';
  req.on('data', (chunk) => {
    data += chunk;
  });

  // 处理 POST 请求
  req.on('end', () => {
    const postData = querystring.parse(data);

    // 做一些处理,这里简单地将数据返回
    res.writeHead(200, { 'Content-Type': 'application/json' });
    res.end(JSON.stringify(postData));
  });
});

// 监听端口
const PORT = 3000;
server.listen(PORT, () => {
  console.log(`Server listening on port ${PORT}`);
});

这只是简单的例子,实际应用中你可能会使用框架(如Express)来简化路由处理和中间件的管理。这些例子主要用于演示基本的 HTTP 请求处理,实际中你可能需要更多的错误处理、安全性和其他功能。


转载请注明出处:http://www.zyzy.cn/article/detail/13167/Node.js