English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Node.js URL analysierenIn diesem Tutorial lernen wir, wie man URLs in Node.js analysiert oder in lesbare Teile zerlegt und die Suchparameter mit dem eingebauten Node.js URL-Modul extrahiert.
Um URLs in Node.js zu analysieren: Verwenden Sie das URL-Modul und können Sie unter Hilfe der Parsing- und Query-Funktionen alle Komponenten der URL extrahieren.
Hier ist eine Schritt-für-Schritt-Anleitung, wie man URLs in Node.js analysiert oder in lesbare Teile zerlegt und die Suchparameter mit dem eingebauten Node.js URL-Modul extrahiert.
步骤1Verwenden Sie das URL-Modul
var url = require(‘url‘); |
第2Schritt: Bringen Sie die URL in die Variable und hier ist unser zu analysierendes Beispiel-URL.
var address = ‘http://localhost:8080/index.php?type=page&action=update&id=5221‘; |
步骤3Verwenden Sie die Parsing-Funktion, um die Website zu analysieren.
var q = url.parse(address,true); |
步骤4:使用点运算符提取HOST,PATHNAME和SEARCH字符串。
q.host q.pathname q.search |
步骤5:使用查询功能解析URL搜索参数。
var qdata = q.query; |
第6步:访问搜索
qdata.type qdata.action qdata.id |
// 包含网址模块 var url = require('url'); var address = 'http://localhost:8080/index.php?type=page&action=update&id=5221'; var q = url.parse(address, true); console.log(q.host); //返回'localhost:8080' console.log(q.pathname); //返回'/index.php' console.log(q.search); //returns '?type=page&action=update&id=5221' var qdata = q.query; // 返回一个对象:{类型:页面,操作:'update',id ='5221} console.log(qdata.type); //返回“页面” console.log(qdata.action); //返回“更新” console.log(qdata.id); //返回“ 5221”
终端输出
$ node urlParsingExample.js localhost:8080 /index.php ?type=page&action=update&id=5221 page update 5221
在本Node.js教程–解析URL中,我们学习了如何使用内置的Node.js URL模块将URL解析或拆分为Node.js中的可读部分。并提取主机,路径名,搜索和搜索参数。