以下是用 Node.js 写一套 HTTP Server 的代码,包含路由、POST、GET:

const http = require('http');
const url = require('url');
const querystring = require('querystring');

// 定义路由
const routes = {
  'GET': {
    '/': (req, res) => {
      res.writeHead(200, {'Content-Type': 'text/html'});
      res.write('<h1>Home Page</h1>');
      res.end();
    },
    '/about': (req, res) => {
      res.writeHead(200, {'Content-Type': 'text/html'});
      res.write('<h1>About Page</h1>');
      res.end();
    },
  },
  'POST': {
    '/api/login': (req, res) => {
      let body = '';
      req.on('data', chunk => {
        body += chunk.toString();
      });
      req.on('end', () => {
        const {username, password} = querystring.parse(body);
        if (username === 'admin' && password === '123456') {
          res.writeHead(200, {'Content-Type': 'application/json'});
          res.write(JSON.stringify({success: true}));
        } else {
          res.writeHead(401, {'Content-Type': 'application/json'});
          res.write(JSON.stringify({success: false}));
        }
        res.end();
      });
    },
  },
};

// 创建http server
http.createServer((req, res) => {
  const method = req.method;
  const path = url.parse(req.url, true).pathname;
  const handler = routes[method][path];
  if (handler) {
    handler(req, res);
  } else {
    res.writeHead(404, {'Content-Type': 'text/html'});
    res.write('<h1>404 Not Found</h1>');
    res.end();
  }
}).listen(3000, () => {
  console.log('Server running at http://localhost:3000/');
});

这段代码中,我们首先定义了一个路由对象routes,其中包含了 GET 请求的两个路由 //about,以及 POST 请求的一个路由 /api/login

然后我们创建了一个 HTTP server,并在其中通过解析请求的 method 和 path,找到对应的路由处理函数,并执行之。

对于 GET 请求,直接返回对应的 HTML 页面;对于 POST 请求,读取请求体中的参数,判断用户名和密码是否正确,返回相应的结果。

最后我们监听 3000 端口,并在控制台输出相应的提示信息。

Node.js HTTP Server: 实现路由、GET 和 POST 请求

原文地址: https://www.cveoy.top/t/topic/mkZC 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录