2021 年
以上答案工作正常,但文档不喜欢,因为url.parse 现在是legacy,所以如果你想对url 进行更多控制,我建议你使用new URL() 函数。
高速公路
您可以从下面的代码中获取Full URL。
`${req.protocol}://${req.get('host')}${req.originalUrl}`
示例网址:http://localhost:5000/a/b/c?d=true&e=true#f=false
固定属性(您将在所有路线中获得相同的结果)
req.protocol: http
req.hostname: localhost
req.get('Host'): localhost:5000
req.originalUrl: /a/b/c?d=true&e=true
req.query: { d: 'true', e: 'true' }
Not Fixed Properties(每条路线都会发生变化,因为它由 express 自己控制)
路线:/
req.baseUrl: <blank>
req.url: /a/b/c?d=true&e=true
req.path: /a/b/c
路由/a
req.baseUrl: /a
req.url: /b/c?d=true&e=true
req.path: /b/c
文档:http://expressjs.com/en/api.html#req.baseUrl
网址打包方式
在URL 函数中,您将在每条路由中获得相同的结果,因此属性始终是固定的。
属性
const url = new URL(`${req.protocol}://${req.get('host')}${req.originalUrl}`);
console.log(url)
您将获得如下结果。我根据图像更改了属性的顺序,以便它可以匹配图像流。
URL {
href: 'http://localhost:5000/a/b/c?d=true&e=true',
protocol: 'http:',
username: '',
password: '',
hostname: 'localhost',
port: '5000',
host: 'localhost:5000',
origin: 'http://localhost:5000',
pathname: '/a/b/c',
search: '?d=true&e=true',
searchParams: URLSearchParams { 'd' => 'true', 'e' => 'true' },
hash: ''
}
注意:Hash 无法发送到服务器,因为它在服务器中被视为Fragment,但您会在客户端即浏览器中得到它。
文档:https://nodejs.org/api/url.html#url_new_url_input_base