[英]Node.js / JavaScript: get all parts of URL path hierarchy
我知道您可以獲得類似以下網址的查詢字符串:
var url = require("url");
...
http.createServer((req,res) => console.log(url.parse(req.url).query))
但這僅在變量采用查詢字符串格式的情況下:
example.com/index.html?key=val&key2=val2
等等...
但是,如果我想以值的形式獲取“變量”,而網址是以下格式,該怎么辦:
example.com/key/val/key2/val2
?
我可以將數組拆分為/
,然后相應地映射它:
var pathParts = request.url.split("/").filter(x => x.length > 0).map(x => x.split("%20").join(" "));
但這對於這樣的URL將失敗:
example.com/url/http://google.com
那么,即使存在嵌套的/,如何獲取用/
分隔的每個值作為唯一的數組元素呢?
首先,當您創建一個url時,需要使用encodeURIComponent()
對它的每個部分進行編碼。 這樣,您將獲得一個網址,例如: example.com/url1/http%3A%2F%2Fgoogle.com/url2/http%3A%2F%2Fbing.com
。 然后將其讀回就像使用以下命令一樣簡單:
let requestArray = request.url.split("/")
let requestDecodedArray = requestArray.map((el)=>decodeURIComponent(el))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.