简体   繁体   English

使用构造函数在 Node 中解析没有协议的 URL

[英]Parse URL without protocol in Node using constructor

How can I parse successfully www.stackoverflow.com as a URL using the WHATWG URL API in NodeJS?如何使用www.stackoverflow.com中的WHATWG URL API将 www.stackoverflow.com 成功解析为 URL?

If I try new URL("www.stackoverflow.com") I get the error error: URL constructor: www.stackoverflow.com is not a valid URL .如果我尝试new URL("www.stackoverflow.com")我会收到错误 error: URL constructor: www.stackoverflow.com is not a valid URL

Note: url.parse is deprecated注意: url.parse弃用

Simply do this:只需这样做:

const parsedURL = new URL(url.startsWith("http") ? url : `https://${url}`);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM