第6天

作者: b02e63527e54 | 来源:发表于2016-10-27 09:56 被阅读0次

    1.url的获取
    var server = http.createServer(function(req,res){
    pathname = url.parse(req.url).pathname;
    console.log(pathname);
    if(pathname == '/'){
    res.write('jwr');
    res.end();
    }else{
    res.write(pathname);

    res.end();
    }
    });
    server.listen(port,ip);
    2.前端读取
    var http = require('http');
    var url = require('url');
    var fs = require('fs');
    //在这里一般端口3000以上
    var port = 12342;
    var ip = '192.168.1.105';
    var server = new http.Server();// 调用http中server方法
    server.listen(port,ip);//开始接听
    server.on('request',(req,res) => {
    //获取得到url地址
    var pathname = url.parse(req.url).pathname;
    switch(pathname){
    case "" || "/":
    // fs获取当前index.html的文件内容
    fs.readFile("./index.html",(err, content) =>{
    if(err){
    res.writeHead(404,{'content-tyle':'text/plain;charset="utf-8"'});
    res.write(err.message);
    res.end();
    }else{
    res.writeHead(200,{'content-tyle':'text/html;charset="utf-8"'});
    res.write(content);
    res.end();
    }
    });
    break;
    default:
    //查看url的格式
    var filename = pathname.substring(1);
    console.log(filename);
    var type = ' ';

        //调用自定义方法getType
    

    getType(filename.substring(filename.lastIndexOf('.')+1));
    fs.readFile(filename,(err, content) =>{
    if(err){
    res.writeHead(404,{'content-tyle':'text/plain;charset="utf-8"'});
    res.write(err.message);
    res.end();
    }else{
    res.writeHead(200,{'content-tyle':'text/html;charset="utf-8"'});
    res.write(content);
    res.end();
    }
    });

    }

    });

    function getType(endtag){
    var type = null;
    switch(endtag){
    case "css":
    type = "text/css;charset='utf-8'"
    break;
    case "js":
    type = "text/javascript;charset='utf-8'"
    break;
    case "htm":
    type = "text/html;charset='utf-8'"
    break;

        default:
    

    }
    //一定以函数记得要返回值
    return type;
    }

    相关文章

      网友评论

          本文标题:第6天

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