路由

// 1 引入系统模块
const http = require('http');
const url = require('url');
// 2 创建网站服务
const app = http.createServer();
// 3为网站服务器对象添加请求事件
app.on('request', (req, res) => {
    // 4 实现路由功能  
    //    4.1 获取请求方式 并且 转换成小写
    const method = req.method.toLowerCase();
    //    4.2 获取请求地址
    const pathname = url.parse(req.url).pathname;

    res.writeHead(200, {
        'content-type': 'text/plain;charset=utf8'
    });
    // 判断请求方式
    if (method == 'get') {

        if (pathname == '/' || pathname == '/index') {
            res.end('<h2>欢迎来到首页...</h2>');
        } else if (pathname == '/list') {
            res.end('欢迎来到列表页...');
        } else {
            res.end('您访问的页面不存在...');
        }

    } else if (method == 'post') {

    }
    res.end('ok...');
})

app.listen(3000);
console.log('服务器启动成功...');
原文地址:https://www.cnblogs.com/ericblog1992/p/13084960.html