美文网首页
NodeJS-url模块

NodeJS-url模块

作者: 走停2015_iOS开发 | 来源:发表于2018-07-02 11:44 被阅读8次
    • 导入模块创建服务
    var http = require('http');
    var url = require('url');
    var server = http.createServer();
    
    • 处理response
    server.on('request',function(req,res){
    
        //req.url :访问路径
        //console.log(req.url);///a/b/1.html
        //解析URL
       var  urlStr = url.parse(req.url);
        console.log(urlStr);
        //Url {
        //protocol: null,
        //    slashes: null,
        //    auth: null,
        //    host: null,
        //    port: null,
        //    hostname: null,
        //    hash: null,
        //    search: '?a=1',
        //    query: 'a=1',
        //    pathname: '/a/b/1.html',
        //    path: '/a/b/1.html?a=1',
        //    href: '/a/b/1.html?a=1' }
        switch (urlStr.pathname)
        {
            case '/':
                //首页
                res.writeHead(200,{
                    'content-type':'text/html;charset=utf-8',
                })
                res.end('<h1>这是首页<h1>');
                break;
            case '/user':
                res.writeHead(200,{
                    'content-type':'text/html;charset=utf-8',
                })
                res.end('<h1>个人中心<h1>');
                break;
            default :
                //处理其他的情况
                res.writeHead(404,{
                    'content-type':'text/html;charset=utf-8',
                })
                res.end('<h1>页面出现错误<h1>');
                break;
                break;
        }
    
    });
    
    • 监听
    server.listen('8080','localhost');
    

    相关文章

      网友评论

          本文标题:NodeJS-url模块

          本文链接:https://www.haomeiwen.com/subject/gvgkuftx.html