以下是用nodeJS写一套httpserver的代码,包含rout、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端口,并在控制台输出相应的提示信息。

用nodeJS写一套httpserver的代码rout、post、get

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

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