特性:
为什么用?在调用 HTTP API 时,通常需要在 URL 中添加动态参数:
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
}
正如你所看到的,这个最小的例子已经很难阅读了。这也是不正确的:
我可以使用内置的 URL 类来防止重复的斜杠和 URLSearchParams 来转义查询字符串。但我仍然需要手动转义所有路径参数。
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
}
如此简单的任务,却又很难读,写也很乏味!这是这个小型库可以帮助您的地方:
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 分发。(Zip 下载和 CDN 即将推出)。
npm install --save urlcat
官方支持 Node 10 及更高版本。由于代码在内部使用 URL 和 URLSearchParams 类,它们在 v10 以下不可用,因此我们无法支持这些版本。
要构建完整的 URL(最常见的用例):
const urlcat = require('urlcat').default;
要使用任何一个实用函数:
const { query, subst, join } = require('urlcat');
要使用所有导出的函数:
const { default: urlcat, query, subst, join } = require('urlcat');
官方支持 TypeScript 2.1 及更高版本。
要构建完整的 URL(最常见的用例):
import urlcat from 'urlcat';
要使用任何一个实用函数:
import { query, subst, join } from 'urlcat';
要使用所有导出的函数:
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
例如:
使用指定的键值对构建查询字符串。键和值被转义,然后由 '&' 字符连接。
例如:
|
result |
|
|
|
|
|
|
|
|
用模板字符串中的值替换参数。模板可能包含 0 个或多个参数占位符。占位符以冒号 (:) 开头,后跟只能包含大写或小写字母的参数名称。在模板中找到的任何占位符都将替换为 params中相应键下的值。
例如
|
|
result |
|
|
|
|
|
|
|
|
|
|
|
|
仅使用一个分隔符连接两个部分。如果分隔符出现在 part1 的末尾或 part2 的开头,则将其删除,然后使用分隔符连接两个部分。
例如:
|
|
|
result |
|
|
|
|
|
|
| |
|
|
| |
|
|
|
Github库地址:https://github.com/balazsbotond/urlcat
分享文章:Urlcat:JavaScript的URL构建器库
网站路径:http://www.mswzjz.cn/qtweb/news10/333010.html
攀枝花网站建设、攀枝花网站运维推广公司-贝锐智能,是专注品牌与效果的网络营销公司;服务项目有等
声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 贝锐智能