Node.js的url.parse()和path名属性
我正在阅读Node.js入门书,名为The Node Beginner Book ,下面的代码(本书给出)我不明白path名属性挂在parsing方法的意义。 所以我想知道它在做什么。 这个方法的文档对我来说是不清楚的
var pathname = url.parse(request.url) .pathname;
var http = require("http"); var url = require("url"); function start(route, handle) { function onRequest(request, response) { var pathname = url.parse(request.url).pathname; // I don't understand the pathname property console.log("Request for " + pathname + " received."); route(handle, pathname); response.writeHead(200, {"Content-Type": "text/plain"}); response.write("Hello World"); response.end(); }
\
pathname
是URL的path部分,位于主机之后和查询之前,包括初始斜线(如果存在)。
例如:
url.parse('http://stackoverflow.com/questions/17184791').pathname
会给你:
"/questions/17184791"
url.parse(urlString [,parseQueryString [,slashesDenoteHost]])
urlString:要分析的URLstring。
parseQueryString:如果为true,查询属性将始终设置为查询string模块的parse()方法返回的对象。
slashesDenoteHost:如果为true,则在//之后的第一个标记将被解释为主机
所以,url.parse()方法接受一个URLstring,parsing它,然后返回一个URL对象。
从而,
var pathname = url.parse(request.url).pathname;
将返回主机的path名称,后跟“/”
例如:
var pathname = url.parse( https://nodejs.org/docs/latest/api/url.html) .pathname
将返回“/docs//latest/api/url.html”
这是一个例子:
var url = "https://u:p@www.example.com:777/a/b?c=d&e=f#g"; var parsedUrl = require('url').parse(url); ... protocol https: auth u:p host www.example.com:777 port 777 hostname www.example.com hash #g search ?c=d&e=f query c=d&e=f pathname /a/b path /a/b?c=d&e=f href https://www.example.com:777/a/b?c=d&e=f#g
另一个:
var url = "http://example.com/"; var parsedUrl = require('url').parse(url); ... protocol http: auth null host example.com port null hostname example.com hash null search null query null pathname / path / href http://example.com/
Node.js文档: URL对象