nodejs创建web服务-静态资源请求-过滤ico图片请求

 服务器端资源路径

node-web服务创建 

//引入模块
const http = require("http");
const urlObj = require("url");
const pathObj = require("path");
const fs = require("fs");

//创建web页面服务
const server = http.createServer((req, res) => {
    //过滤ico图片请求
    if (req.url === "/favicon.ico") {
        res.end();
    } else {
        //获取请求路径
        let { pathname } = urlObj.parse(req.url, true);///www/index.html
        //判断 是否是根目录
        if (pathname === "/") { //当访问根 默认访问index.html
            pathname = "/index.html";
        }
        //获取扩展名
        let { ext } = pathObj.parse(pathname);
        //设置响应头信息
        res.writeHead(200, { "Content-type": getMine(ext)+";charset=UTF-8"});
        console.log(pathname,ext,getMine(ext));
        //响应相应文件
        res.end(fs.readFileSync("." + pathname));
    }

});
function getMine(ext) {
    switch (ext) {
        case ".html": return "text/html";
        case ".css": return "text/css";
        case ".js": return "text/html";
        case ".jpg": return "image/jpeg";
        case ".jpeg": return "image/jpeg";
        case ".json": return "application/json";
        default: return "text/plan";
    }
}
//设置端口
server.listen(3000);

后台服务打印信息 

请求地址                         文件扩展名             文件类型

/www/index.html                 .html                    text/html
/www/css/index.css            .css                      text/css
/www/img/01.jpg                 .jpg                     image/jpeg
/www/js/index.js                  .js                         text/html

posted @   JackieDYH  阅读(5)  评论(0编辑  收藏  举报  
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 25岁的心里话
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示