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
本文来自博客园,作者:JackieDYH,转载请注明原文链接:https://www.cnblogs.com/JackieDYH/p/17634701.html