Javascript 在 Node.js 中验证 URL
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30931079/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Validating a URL in Node.js
提问by Arslan Sohail
I want to validate a URL of the types:
我想验证以下类型的 URL:
www.google.com
http://www.google.com
google.com
www.google.com
http://www.google.com
google.com
using a single regular expression, is it achievable? If so, kindly share a solution in JavaScript.
使用单个正则表达式,是否可以实现?如果是这样,请在 JavaScript 中分享解决方案。
Please note I only expect the underlying protocols to be HTTP or HTTPS. Moreover, the main question on hand is how can we map all these three patterns using one single regex expression in JavaScript? It doesn't have to check whether the page is active or not. If the value entered by the user matches any of the above listed three cases, it should return true
on the other hand if it doesn't it should return false
.
请注意,我只希望底层协议是 HTTP 或 HTTPS。此外,手头的主要问题是我们如何使用 JavaScript 中的一个正则表达式来映射所有这三种模式?它不必检查页面是否处于活动状态。如果用户输入的值与上面列出的三种情况中的任何一种匹配,则应返回true
,否则应返回false
。
回答by Jossef Harush
Checking if a URL is live
检查URL是活
This is a bit of a hack, but if I required to do so, this is how i would approach it:
这有点像黑客,但如果我需要这样做,这就是我的处理方式:
1st step
第一步
Parse and extract the domain/ip from the given url
从给定的 url 解析并提取域/ip
http://drive.google.com/0/23 ? drive.google.com
HTTP:// drive.google.com/ 0/23?drive.google.com
This is how to do that in nodejs:
这是如何在 nodejs 中做到这一点:
var url = require("url");
var result = url.parse('http://drive.google.com/0/23');
console.log(result.hostname);
2nd step
第二步
pingthe extracted domain/ip - not all servers will respond to ICMP (PING) requests due to network configuration.
ping提取的域/ip - 由于网络配置,并非所有服务器都会响应 ICMP (PING) 请求。
var ping = require ("net-ping");
var session = ping.createSession ();
session.pingHost (target, function (error, target) {
if (error)
console.log (target + ": " + error.toString ());
else
console.log (target + ": Alive");
});
- check out net-pingpackage
- 查看net-ping包
3rd step
第三步
You can perform an HTTP HEAD request to that url and check the status code.
您可以对该 url 执行 HTTP HEAD 请求并检查状态代码。
var request = require('request');
request({method: 'HEAD', uri:'http://www.google.com'}, function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body) // Show the HTML for the Google homepage.
}
})
- It's a bit risky if this is a web-service (since you can trigger actions).
- Would be more complicated if the url requires authentication / redirection
- @Jan J?na commented that it's better to use HEAD. He's completely right. Note that not all web servers support
HEAD
method - Check out the requestpackage
- 如果这是一个网络服务(因为您可以触发操作),则有点冒险。
- 如果 url 需要身份验证/重定向会更复杂
- @Jan J?na 评论说最好使用 HEAD。他是完全正确的。请注意,并非所有 Web 服务器都支持
HEAD
方法 - 查看请求包
There's a Package for that!
有一个包!
You can use the existing nodejs package called validUrl
您可以使用名为validUrl的现有 nodejs 包
usage:
用法:
var validUrl = require('valid-url');
var url = "http://bla.com"
if (validUrl.isUri(url)){
console.log('Looks like an URI');
}
else {
console.log('Not a URI');
}
Installation:
安装:
npm install valid-url --save
If you still want a simple REGEX
如果你还想要一个简单的 REGEX
google is your friend. check this out
谷歌是你的朋友。看一下这个
回答by pouya
There is no need to use a third party library.
无需使用第三方库。
To check if a string is a valid URL
检查字符串是否是有效的 URL
const URL = require("url").URL;
const stringIsAValidUrl = (s) => {
try {
new URL(s);
return true;
} catch (err) {
return false;
}
};
stringIsAValidUrl("https://www.example.com:777/a/b?c=d&e=f#g"); //true
stringIsAValidUrl("invalid"): //false
Edit
编辑
If you need to restrict the protocol to a range of protocols you can do something like this
如果您需要将协议限制为一系列协议,您可以执行以下操作
const { URL, parse } = require('url');
const stringIsAValidUrl = (s, protocols) => {
try {
new URL(s);
const parsed = parse(s);
return protocols
? parsed.protocol
? protocols.map(x => `${x.toLowerCase()}:`).includes(parsed.protocol)
: false
: true;
} catch (err) {
return false;
}
};
stringIsAValidUrl('abc://www.example.com:777/a/b?c=d&e=f#g', ['http', 'https']); // false
stringIsAValidUrl('abc://www.example.com:777/a/b?c=d&e=f#g'); // true
回答by MSi
The "valid-url" npm package did not work for me. It returned valid, for an invalid url. What worked for me was "url-exists"
“valid-url” npm 包对我不起作用。对于无效的网址,它返回有效。对我有用的是“url-exists”
const urlExists = require("url-exists");
urlExists(myurl, function(err, exists) {
if (exists) {
res.send('Good URL');
} else {
res.send('Bad URL');
}
});
回答by Anas Tiour
I am currently having the same problem, and Pouya's answer will do the job just fine. The only reason I won't be using it is because I am already using the NPM package validate.jsand it can handle URLs.
我目前遇到了同样的问题,Pouya 的回答可以很好地完成这项工作。我不会使用它的唯一原因是我已经在使用 NPM 包validate.js并且它可以处理 URLs。
As you can see from the document, the URL validator the regular expression based on this gistso you can use it without uing the whole package.
正如您从文档中看到的,URL 验证器基于此gist的正则表达式,因此您可以在不使用整个包的情况下使用它。
I am not a big fan of Regular Expressions, but if you are looking for one, it is better to go with a RegEx used in popular packages.
我不是正则表达式的忠实粉丝,但如果您正在寻找正则表达式,最好使用流行包中使用的正则表达式。