内置URL模块
URL模块可用于解析web地址。
要包含URL模块,使用require()
方法:
var url = require('url');
使用url.parse()
方法解析一个网址,将返回一个URL对象,对象中包含了解析结果:
示例
解析网址:
var url = require('url');
var adr = 'http://localhost:8080/default.htm?year=2017&month=february';
var q = url.parse(adr, true);
console.log(q.host); //返回 'localhost:8080'
console.log(q.pathname); //返回 '/default.htm'
console.log(q.search); //返回 '?year=2017&month=february'
var qdata = q.query; //返回对象: { year: 2017, month: 'february' }
console.log(qdata.month); //返回 'february'
Node.js 文件服务器
现在,我们知道了如何解析查询字符串,在前一章中,我们学习了如何使用文件系统模块。让我们将两者结合起来,创建一个文件服务器。
当前目录下,创建两个html文件。
summer.html
<!DOCTYPE html>
<html>
<body>
<p>Summer</p>
<p>I love the sun!</p>
</body>
</html>
winter.html
<!DOCTYPE html>
<html>
<body>
<p>Winter</p>
<p>I love the snow!</p>
</body>
</html>
创建一个js文件,主要功能是,把被请求文件的内容返回给客户端。如果出现错误,报404错误:
demo_fileserver.js:
var http = require('http');
var url = require('url');
var fs = require('fs');
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);
启动demo_fileserver.js:
C:\Users\Your Name>node demo_fileserver.js
使用浏览器,访问以下地址:
http://localhost:8080/summer.html
输出:
Summer
I love the sun!
http://localhost:8080/winter.html
输出:
Winter
I love the snow!