使用节点的
URL
API,还有一些人工检查。
-
手动检查URL是否具有有效的协议。
-
实例化url。
-
检查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)
}
我只使用
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 â
âââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ