如何规范化 URL?

Vic*_*tor 7 url node.js

我正在处理需要用户输入各种 URL(例如:用于他们的个人资料)的情况。但是,用户并不总是以该https://example.com格式插入 URL 。他们可能会插入如下内容:

  • example.com
  • example.com/
  • example.com/somepage
  • 但类似的东西me@example.com或其他东西不应该被接受

如何将 URL 规范化为可能指向 Web 地址的格式?我在网络浏览器中看到了这种行为。我们几乎总是在网络浏览器的栏中输入蹩脚的内容,他们可以区分这是搜索还是可以转换为 URL 的内容。

我尝试在很多地方寻找,但似乎找不到任何方法。

如果可能的话,我更喜欢为 Node 编写的解决方案。非常感谢!

now*_*owy 5

使用节点的URL API,以及一些手动检查。

  1. 手动检查 URL 是否具有有效的协议。
  2. 实例化 URL。
  3. 检查 URL 是否不包含附加信息。

示例代码:

const { URL } = require('url')
let myTestUrl = 'https://user:pass@sub.host.com:8080/p/a/t/h?query=string#hash';

try {
  if (!myTestUrl.startsWith('https://') && !myTestUrl.startsWith('http://')) {
    // The following line is based on the assumption that the URL will resolve using https.
    // Ideally, after all checks pass, the URL should be pinged to verify the correct protocol.
    // Better yet, it should need to be provided by the user - there are nice UX techniques to address this.
    myTestUrl = `https://${myTestUrl}`
  }

  const normalizedUrl = new URL(myTestUrl);

  if (normalizedUrl.username !== '' || normalized.password !== '') {
    throw new Error('Username and password not allowed.')
  }

  // Do your thing
} catch (e) {
  console.error('Invalid url provided', e)
}
Run Code Online (Sandbox Code Playgroud)

在这个例子中,我只使用了http和https,作为一个要点。

直接来自文档,API 的一个很好的可视化:

???????????????????????????????????????????????????????????????????????????????????????????????
?                                            href                                             ?
???????????????????????????????????????????????????????????????????????????????????????????????
? protocol ?  ?        auth         ?        host         ?           path            ? hash  ?
?          ?  ?                     ???????????????????????????????????????????????????       ?
?          ?  ?                     ?   hostname   ? port ? pathname ?     search     ?       ?
?          ?  ?                     ?              ?      ?          ??????????????????       ?
?          ?  ?                     ?              ?      ?          ? ?    query     ?       ?
"  https:   //    user   :   pass   @ sub.host.com : 8080   /p/a/t/h  ?  query=string   #hash "
?          ?  ?          ?          ?   hostname   ? port ?          ?                ?       ?
?          ?  ?          ?          ???????????????????????          ?                ?       ?
? protocol ?  ? username ? password ?        host         ?          ?                ?       ?
???????????????????????????????????????????????????????????          ?                ?       ?
?   origin    ?                     ?       origin        ? pathname ?     search     ? hash  ?
???????????????????????????????????????????????????????????????????????????????????????????????
?                                            href                                             ?
???????????????????????????????????????????????????????????????????????????????????????????????
Run Code Online (Sandbox Code Playgroud)


Sin*_*hus 5

您想要的normalize-url包裹:

const normalizeUrl = require('normalize-url');

normalizeUrl('example.com/');
//=> 'http://example.com'
Run Code Online (Sandbox Code Playgroud)

它对 URL 进行一系列规范化。

  • 请注意,此软件包并不正式支持浏览器环境。如果您使用旧的浏览器,很可能会出现错误。 (2认同)