nodejs创建web服务-静态资源请求-过滤ico图片请求
发布日期:2021-06-30 11:51:15 浏览次数:2 分类:技术文章

本文共 1278 字,大约阅读时间需要 4 分钟。

 服务器端资源路径

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

转载地址:https://jackiehao.blog.csdn.net/article/details/106105801 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:js中encodeURIComponent和decodeURIComponent函数使用
下一篇:一篇博文让你轻松搞懂TCP与UDP的区别

发表评论

最新留言

留言是一种美德,欢迎回访!
[***.207.175.100]2024年04月21日 11时48分39秒

关于作者

    喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!

推荐文章