Node.js-简单路由器控制

简易HTTP服务器搭建
本文介绍了一个使用Node.js实现的简易HTTP服务器,该服务器能够处理多种类型的请求并返回静态资源如HTML页面、图片和CSS样式文件。通过对不同URL路径的判断,服务器能返回相应的文件内容或者错误提示。

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%;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值