ホームページ  >  記事  >  ウェブフロントエンド  >  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:

rreee

関連するおすすめ:

Nodejsルーティングとコントローラーの使用法

以上がNode.jsでのルーター制御の実装コードの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。