首頁  >  文章  >  web前端  >  Node.js中路由器控制的實作程式碼

Node.js中路由器控制的實作程式碼

不言
不言原創
2018-08-23 17:11:081156瀏覽

這篇文章帶給大家的內容是關於Node.js中路由器控制的實作程式碼,有一定的參考價值,有需要的朋友可以參考一下,希望對你有幫助。

render.js:

//引入模块
let http = require("http");
let fs = require("fs");

//创建HTTP服务
http.createServer(function (req,res) {

    if (req.url === "/favicon.ico"){
        return false;
    }
    if (req.url === "/" || req.url === "/index.html"){
        // 读取文件
        fs.readFile("./index.html",function (err,data) {
            //设置响应头
            res.writeHead(200,{
                "Content-type":"text/html;charset=utf-8"
            });

            //结束响应
            res.end(data);
        })
    }else if(req.url === "/show.html"){
        // 读取文件
        fs.readFile("./show.html",function (err,data) {
            //设置响应头
            res.writeHead(200,{
                "Content-type":"text/html;charset=utf-8"
            });

            //结束响应
            res.end(data);
        })
    }else if(req.url === "/image/1.jpg" ){
        //读取文件
        fs.readFile("./image/1.jpg",function (err,data) {
            //设置响应头
            res.writeHead(200,{
                "Content-type":"image/jpeg"
            });
            //结束响应
            res.end(data);
        })
    }else if(req.url === "/style.css"){
        //读取文件
        fs.readFile("./style.css",function (err,data) {
            //设置响应头
            res.writeHead(200,{
                "Content-type":"text/css"
            });
            // 结束响应
            res.end(data);
        })
    } else {
        res.writeHead(404,{
            "Content-type":"text/html;charset=utf-8"
        });
        res.end("您访问的也没不存在");
    }
    console.log(req.url);
}).listen(3200,function () {
    console.log("Http Server running on port 3200");
})

index.html:

<h1>你好</h1>
<img src="/image/1.jpg" alt="">

show.html:

<h1>你好,全世界</h1>

#style.css:

h1 {
    font-size: 18px;
}
img{
    width: 50%;
}

相關推薦:

Nodejs路由與控制器的使用

以上是Node.js中路由器控制的實作程式碼的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn