掃二維碼與項(xiàng)目經(jīng)理溝通
我們在微信上24小時期待你的聲音
解答本文疑問/技術(shù)咨詢/運(yùn)營咨詢/技術(shù)建議/互聯(lián)網(wǎng)交流
特性:

為什么用?在調(diào)用 HTTP API 時,通常需要在 URL 中添加動態(tài)參數(shù):
const API_URL = 'https://api.example.com/';
function getUserPosts(id, blogId, limit, offset) {
const requestUrl = `${API_URL}/users/${id}/blogs/${blogId}/posts?limit=${limit}&offset=${offset}`;
// send HTTP request
}
正如你所看到的,這個最小的例子已經(jīng)很難閱讀了。這也是不正確的:
我可以使用內(nèi)置的 URL 類來防止重復(fù)的斜杠和 URLSearchParams 來轉(zhuǎn)義查詢字符串。但我仍然需要手動轉(zhuǎn)義所有路徑參數(shù)。
const API_URL = 'https://api.example.com/';
function getUserPosts(id, blogId, limit, offset) {
const escapedId = encodeURIComponent(id);
const escapedBlogId = encodeURIComponent(blogId);
const path = `/users/${escapedId}/blogs/${escapedBlogId}`;
const url = new URL(path, API_URL);
url.search = new URLSearchParams({ limit, offset });
const requestUrl = url.href;
// send HTTP request
}
如此簡單的任務(wù),卻又很難讀,寫也很乏味!這是這個小型庫可以幫助您的地方:
const API_URL = 'https://api.example.com/';
function getUserPosts(id, limit, offset) {
const requestUrl = urlcat(API_URL, '/users/:id/posts', { id, limit, offset });
// send HTTP request
}
這個庫會這樣處理:
如何使用?目前,該軟件包通過 npm 分發(fā)。(Zip 下載和 CDN 即將推出)。
npm install --save urlcat
官方支持 Node 10 及更高版本。由于代碼在內(nèi)部使用 URL 和 URLSearchParams 類,它們在 v10 以下不可用,因此我們無法支持這些版本。
要構(gòu)建完整的 URL(最常見的用例):
const urlcat = require('urlcat').default;要使用任何一個實(shí)用函數(shù):
const { query, subst, join } = require('urlcat');要使用所有導(dǎo)出的函數(shù):
const { default: urlcat, query, subst, join } = require('urlcat');
官方支持 TypeScript 2.1 及更高版本。
要構(gòu)建完整的 URL(最常見的用例):
import urlcat from 'urlcat';
要使用任何一個實(shí)用函數(shù):
import { query, subst, join } from 'urlcat';要使用所有導(dǎo)出的函數(shù):
import urlcat, { query, subst, join } from 'urlcat';
import urlcat from 'https://deno.land/x/urlcat/src/index.ts';
console.log(urlcat('https://api.foo.com', ':name', { id: 25, name: 'knpwrs' }));
例如,{ firstParam: 1, 'second-param': 2 } 是一個有效的 ParamMap。
function urlcat(baseUrl: string, pathTemplate: string, params: ParamMap): string
function urlcat(baseUrl: string, pathTemplate: string): string
function urlcat(baseTemplate: string, params: ParamMap): string
例如:
使用指定的鍵值對構(gòu)建查詢字符串。鍵和值被轉(zhuǎn)義,然后由 '&' 字符連接。
例如:
|
? |
result |
|
? |
? |
|
? |
? |
|
? |
? |
|
? |
? |
用模板字符串中的值替換參數(shù)。模板可能包含 0 個或多個參數(shù)占位符。占位符以冒號 (:) 開頭,后跟只能包含大寫或小寫字母的參數(shù)名稱。在模板中找到的任何占位符都將替換為 params中相應(yīng)鍵下的值。
例如
|
? |
? |
result |
|
? |
? |
? |
|
? |
? |
? |
|
? |
? |
? |
|
? |
? |
? |
僅使用一個分隔符連接兩個部分。如果分隔符出現(xiàn)在 part1 的末尾或 part2 的開頭,則將其刪除,然后使用分隔符連接兩個部分。
例如:
|
|
|
|
result |
|
|
|
|
|
|
|
|
| |
|
|
|
| |
|
|
|
|
Github庫地址:https://github.com/balazsbotond/urlcat

我們在微信上24小時期待你的聲音
解答本文疑問/技術(shù)咨詢/運(yùn)營咨詢/技術(shù)建議/互聯(lián)網(wǎng)交流