url.parse(urlString[, parseQueryString[, slashesDenoteHost]])
稳定性: 0 - 已弃用:请改用 WHATWG URL API。
urlString<string> 要解析的 URL 字符串。parseQueryString<boolean> 如果为true,query属性将始终被设置为由querystring模块的parse()方法返回的对象。如果为false,返回的 URL 对象上的query属性将是未解析、未解码的字符串。默认值:false。slashesDenoteHost<boolean> 如果为true,字面字符串//之后并且下一个/之前的第一个标记将被解释为host。例如,给定//foo/bar,结果将是{host: 'foo', pathname: '/bar'}而不是{pathname: '//foo/bar'}。默认值:false。
url.parse() 方法接收一个 URL 字符串,对其进行解析,并返回一个 URL 对象。
【The url.parse() method takes a URL string, parses it, and returns a URL
object.】
如果 urlString 不是字符串,将抛出 TypeError。
【A TypeError is thrown if urlString is not a string.】
如果存在 auth 属性但无法解码,则会抛出 URIError。
【A URIError is thrown if the auth property is present but cannot be decoded.】
url.parse() 使用一种宽松的、非标准的 URL 字符串解析算法。它容易出现诸如 主机名欺骗 的安全问题以及对用户名和密码处理不正确的情况。不要对不可信的输入使用它。url.parse() 的漏洞不会发布 CVE。请改用 WHATWG URL API,例如:
function getURL(req) {
const proto = req.headers['x-forwarded-proto'] || 'https';
const host = req.headers['x-forwarded-host'] || req.headers.host || 'example.com';
return new URL(`${proto}://${host}${req.url || '/'}`);
} 上面的示例假设格式良好的头信息会从反向代理转发到你的 Node.js 服务器。如果你没有使用反向代理,应该使用下面的示例:
【The example above assumes well-formed headers are forwarded from a reverse proxy to your Node.js server. If you are not using a reverse proxy, you should use the example below:】
function getURL(req) {
return new URL(`https://example.com${req.url || '/'}`);
}