node服务器响应浏览器请求的html页面(包括该页面引入的js、css、icon文件等)

运行服务端node index.js后,在浏览器上输入http://localhost:8888/,服务器根据路径判断,返回默认的页面index.html。浏览器得到index.html后,再依次向服务器请求index.html上需加载的css、js、图片等。服务器根据请求的不同后缀,修改对应响应头部,并返回对应文件。若没有该文件,则返回404界面。

Javascript代码:

const http = require("http");
const fs = require("fs");
const url = require("url");
const path = require("path");

http.createServer((req, res) => {

	let pathName = url.parse(req.url).pathname; //转换为url对象

	//默认加载路径
	if(pathName == '/') {
		pathName = "/index.html";
	}

	//获取文件后缀名
	let extName = path.extname(pathName);

	// console.log("../fore_end" + pathName);  //例如../fore_end/css/style.css
	fs.readFile("../fore_end" + pathName, (err, data) => {
		if(err) { //出错则返回404页面
			console.log("404 Not Found!");			
			fs.readFile("../fore_end/404.html", (errorNotFound, dataNotFound) => {
				if(errorNotFound) {
					console.log(errorNotFound);
				} 
				else {
					res.writeHead(200, {"Content-Type": "text/html;charset=utf-8"});
					res.write(dataNotFound); //返回404页面
					res.end();
				}
			})
			return;
		}
		else {
			// 获取对应后缀的文件类型
			let ext = getExt(extName);

			// 设置请求头
			res.writeHead(200, {"Content-Type": ext + "; charset=utf-8"});
			res.write(data); //返回请求文件
			res.end();
		}
	})
}).listen(8888);

// 获取后缀名
getExt = (extName) => {
  switch(extName) {
    case '.html': return 'text/html';
    case '.css': return 'text/css';
    case '.js': return 'text/js';
    default: return 'text/html';
  }
}

要注意,上面返回文件的路径是相对于服务端的index.js文件。

要获取更多的文件类型,可通过读取文件判断。ext.json文件获取

getExt = (extName) => {
	let data = fs.readFileSync("./ext.json");
	let ext = JSON.parse(data.toString()); //转换为js对象
	return ext[extName];
}

对于浏览器请求的 favicon.icon文件,可在html头部添加下面部分。浏览器会向服务器请求favicon.icon

<link rel="shortcut icon" href="img/favicon.icon" />

参考链接:
https://github.com/LiangJunrong/document-library/blob/master/other-library/Node/Node-base.md#chapter-three-ten
https://blog.csdn.net/guzhao593/article/details/93972193(网站 favicon.icon图标的设置)

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值