我正在处理一种情况,我需要用户输入各种 URL(例如:用于他们的个人资料)。但是,用户并不总是以
https://example.com
格式插入 URL。他们可能会插入类似的内容:
example.com
example.com/
example.com/somepage
[email protected]
或其他的东西不应该被接受如何将 URL 规范化为可能生成网址的格式?我在网络浏览器中看到了这种行为。我们几乎总是在网络浏览器的栏中输入蹩脚的东西,它们可以区分这是搜索还是可以转换为 URL 的东西。
我尝试在很多地方寻找,但似乎找不到任何方法。
如果可能的话,我更喜欢为 Node 编写的解决方案。非常感谢!
使用节点的 URL API,以及一些手动检查。
示例代码:
const { URL } = require('url')
let myTestUrl = 'https://user:[email protected]: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)
}
在这个例子中我只使用了
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 │
└─────────────────────────────────────────────────────────────────────────────────────────────┘
normalize-url
套餐:
const normalizeUrl = require('normalize-url');
normalizeUrl('example.com/');
//=> 'http://example.com'
它对 URL 运行一系列规范化。
这里有一个简单的方法:
function normalizeUrl(url: string): string {
const urlObj = new URL(url, window.location.href)
urlObj.searchParams.sort()
return urlObj.href
}
normalizeUrl('foo?b=2&a=1#bar') // 'http://localhost:5173/foo?a=1&b=2#bar'
我已经对查询参数进行了排序,因为通常这些参数的顺序并不重要。相对 URL 将被扩展。
如果您使用 Node.js,您可能需要使用
import.meta.url
而不是 window.location.href
。