Node.js URL模块
使用url.parse()方法可以解析一个地址,并且会返回带有地址和属性的URL对象
var url = require('url');
var adr = 'http://loclahost:8080/index.html?name=admin&passwd=root&id=201822021';
var res = url.parse(adr,true);
console.log("HOST:"+res.host);
console.log("路由名:"+res.pathname);
console.log("搜索值:"+res.search);
var resnew = res.query;
console.log("用户名:"+resnew.name+";密码:"+resnew.passwd+";ID号"+resnew.id);
实战演示,路由设置
创造一个Node.js文件并打开后将制定内容给客户端,如果出现错误,就抛出404错误
urlFilename.js
var url = require('url');
var fs = require('fs');
var http = require('http');
http.createServer(function (req, res) {
var q = url.parse(req.url, true);
//读取路由名作为文件名
var filename = "." + q.pathname;
fs.readFile(filename, function(err, data) {
if (err) {
res.writeHead(404, {'Content-Type': 'text/html'});
return res.end("404 Not Found");
}
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
return res.end();
});
}).listen(8080);
console.log("服务已经成功在8080端口运行!");
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
body{
background-color: black;
padding: 10%;
}
h2{
color: #fff;
}
.container {
width: 80%;
height: 100px;
background-color: rgba(65, 247, 126, 0.84);
padding: 10%;
color: #fff;
text-align: center;
line-height: 100px;
-webkit-box-reflect:below 0px -webkit-gradient(linear, left top, left bottom, from(transparent), color-stop(70%, transparent), to(rgba(250, 250, 250, 0.4)));
border-radius: 12px;
}
</style>
</head>
<body>
<h2>欢迎来到SANET</h2>
<div class="container">
SANET是一个超前的虚拟网络世界,由AI建立起来的硅基文明宇宙
</div>
</body>
</html>
other.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
body{
background-color: black;
padding: 10%;
}
h2{
color: #fff;
}
.container {
width: 80%;
height: 100px;
background-color: rgba(247, 65, 202, 0.84);
padding: 10%;
color: #fff;
text-align: center;
line-height: 100px;
-webkit-box-reflect:below 0px -webkit-gradient(linear, left top, left bottom, from(transparent), color-stop(70%, transparent), to(rgba(250, 250, 250, 0.4)));
border-radius: 12px;
}
</style>
</head>
<body>
<h2>穷人奋斗,励志一生</h2>
<div class="container">
我虽贫穷,但不服现状,努力奋斗的脚印从田地开始,在互联网里将书写属于自己的传奇人生!
</div>
</body>
</html>
演示效果动态图
如果在路由里面输入localhost:8080/other.html后会出现这样的情况
史上最短最敷衍的Nodejs免费视频教程
B站视频讲解演示地址 https://www.bilibili.com/video/BV1KT4y1g7FG/