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/