node.js - nodejs 中相对 url 到绝对 url

标签 node.js relative-path absolute-path relative-url

我有这样的网址:

http://example.com/path/to/css/../../images/test.jpg

我想将其转换为绝对值,如下所示:

http://example.com/path/images/test.jpg

我正在 Nodejs 中寻找一个模块来做同样的事情。 模块 path 做同样的事情。但是(path.resolve)也以目录路径为前缀。

我正在寻找类似的东西,但是是为了 url。

最佳答案

您可以使用 URL 模块。 https://nodejs.org/docs/latest/api/url.html

const { URL } = require('url');
new URL('path/images/test.jpg', 'http://example.com/')

URL {
  href: 'http://example.com/path/images/test.jpg',
  origin: 'http://example.com',
  protocol: 'http:',
  username: '',
  password: '',
  host: 'example.com',
  hostname: 'example.com',
  port: '',
  pathname: '/path/images/test.jpg',
  search: '',
  searchParams: URLSearchParams {},
  hash: '' }

关于node.js - nodejs 中相对 url 到绝对 url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45798453/

相关文章:

javascript - 为什么在 Mongoose 文档中看不到所有 JS 对象属性?

postback - 由于相对路径问题,自定义404页面无法回传

PHP:如何解析相对 URL

html - ASP.net 中 CSS 文件的绝对路径

javascript - 未定义滚动 - 引用错误

node.js - Mongoose 会过滤掉额外的属性吗?

javascript - Node.js 错误日志包含更多信息

Ruby 路径管理

java - 为什么此导入不起作用

bash - 使用 Bash 将给定当前目录的绝对路径转换为相对路径