【问题标题】:Is there a replacement for url.resolve for creating URLs in Node?是否可以替代 url.resolve 在 Node 中创建 URL?
【发布时间】:2021-01-16 09:19:26
【问题描述】:

我在this post 上看到您可以使用 url.resolve 连接 URL:

url.resolve('http://example.com/', 'image.jpg')    // 'http://example.com/image.jpg'

但在阅读documentation 后,我发现它现在已被弃用。 url.resolve 有替代品吗?

【问题讨论】:

  • "已弃用:改用 WHATWG URL API。" - 来自您发布的链接。
  • 抱歉,这听起来很愚蠢,但我在WHATWG URL API 文档中找不到该函数...
  • new URL(input[, base]) -> new URL('/foo', 'https://example.org/'); // https://example.org/foo - 这不是你需要的吗?
  • 是的,这正是我所需要的。我想我很困惑,因为新 URL 返回一个对象,而不是我正在寻找的字符串。然后我只需要使用object.href 来获取href。感谢您的反馈。

标签: node.js url path resolve


【解决方案1】:

好的,在 cmets 的帮助下,我设法找到了解决方案:

const url_object = new URL('image.jpg', 'http://example.com/')
const url_string = url_object.href  // http://example.com/image.jpg

对此有点陌生,我没有意识到我必须将 href 从新 URL 返回的对象中提取出来。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-29
    • 2022-11-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多