过客匆匆,恍如烟

活到老,学到老

原生node.js服务器搭建


//app.js文件部分:

"use strict";
//console.log("hello word");
const http=require("http");
const  fs=require("fs");
const myFirst=require("./routes/resource");
const server=http.createServer(function (request,respones) {
       console.log("有请求");
     // console.log(url);
       let url=request.url;
       let urlAarry=url.split(".");
        if(urlAarry[1]=="html"){
              myFirst.sendHtml(request,respones);
        } else if(urlAarry[1]=="css"){
              myFirst.sendCss(request,respones);
        } else if(urlAarry[1]=="js"){
              myFirst.sendJs(request,respones);
        }else if(urlAarry[1]=="jpg"||urlAarry[1]=="png"|| urlAarry[1]=="icon"){
              myFirst.sendImag(request,respones);

        }


        // respones.writeHead(200,{"content-type":"text/html;charset=utf-8"});
        // respones.write("<h1 style='color: blueviolet'>我是中国人,我为中国感到骄傲</h1>");
        // respones.end();
});
console.log("启动服务器");
server.listen(8888);

//resource.js文件部分

"use strict"
const  fs=require("fs");
exports.sendHtml=function (request,respones) {
    let url=request.url;
    fs.readFile("public"+url,"utf-8",function (err,data) {
        if(err==0||err==undefined){
            respones.writeHead(200,{"content-type":"text/html;utf-8"});
            respones.write(data);
            respones.end();
        }
    });
};
exports.sendCss=function (request,respones) {
    let url=request.url;
    fs.readFile("public"+url,"utf-8",function (err,data) {
        if(err==0||err==undefined){
            respones.writeHead(200,{"content-type":"text/css;utf-8"});
            respones.write(data);
            respones.end();
        }
    });
};
exports.sendJs=function (request,respones) {
    let url=request.url;
    fs.readFile("public"+url,"utf-8",function (err,data) {
        if(err==0||err==undefined){
            respones.writeHead(200,{"content-type":"text/javascript;utf-8"});
            respones.write(data);
            respones.end();
        }
    });
};
exports.sendImag=function (request,respones) {
    let url=request.url;
    fs.readFile("public"+url,function (err,data) {
        if(err==0||err==undefined){
            respones.writeHead(200,{"content-type":"text/jpg"});
            respones.write(data);
            respones.end();
        }
    });
};




阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_33559304/article/details/53997086
上一篇node.js之express简单地框架登陆请求和相应
下一篇JavaScript中null和undefined的区别
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭