温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

JavaScript的库urlcat有什么作用

发布时间:2022-02-17 13:43:32 来源:亿速云 阅读:96 作者:iii 栏目:开发技术

本篇内容主要讲解“JavaScript的库urlcat有什么作用”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“JavaScript的库urlcat有什么作用”吧!

urlcat 是一个小型的 JavaScript 库,它使构建 URL 非常方便并防止常见错误;

JavaScript的库urlcat有什么作用

特性:

  • 友好的 API

  • 无依赖

  • 压缩后0.8KB大小

  • 提供TypeScript类型

1.作用

在调用 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
}

正如你所看到的,这个最小的例子已经很难阅读了。这也是不正确的:

  • 我忘记了 API_URL 常量末尾有一个斜杠,所以这导致了一个包含重复斜杠的URL(https://api.example.com//users)

  • 嵌入的值需要使用 encodeURIComponent 进行转义

我可以使用内置的 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
}

这个库会这样处理:

  • 转义所有参数

  • 将所有部分连接起来(它们之间总是正好有一个 / 和 ?)

2.使用方法

目前,该软件包通过 npm 分发。 (Zip 下载和 CDN 即将推出)。

npm install --save urlcat

在Node.js中使用

官方支持 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中使用

官方支持 TypeScript 2.1 及更高版本。

要构建完整的 URL(最常见的用例):

import urlcat from 'urlcat';

要使用任何一个实用函数:

import { query, subst, join } from 'urlcat';

要使用所有导出的函数:

import urlcat, { query, subst, join } from 'urlcat';

在Deno中使用

import urlcat from 'https://deno.land/x/urlcat/src/index.ts';

console.log(urlcat('https://api.foo.com', ':name', { id: 25, name: 'knpwrs' }));

3.API

ParamMap:具有字符串键的对象

例如:{ firstParam: 1, 'second-param': 2 } 是一个有效的 ParamMap

urlcat:构建完整的 URL

function urlcat(baseUrl: string, pathTemplate: string, params: ParamMap): string
function urlcat(baseUrl: string, pathTemplate: string): string
function urlcat(baseTemplate: string, params: ParamMap): string

例如:

urlcat('https://api.example.com', '/users/:id/posts', { id: 123, limit: 10, offset: 120 })
→ 'https://api.example.com/users/123/posts?limit=10&offset=120'
urlcat('http://example.com/', '/posts/:title', { title: 'Letters & "Special" Characters' })
→ 'http://example.com/posts/Letters%20%26%20%22Special%22%20Characters'
urlcat('https://api.example.com', '/users')
→ 'https://api.example.com/users'
urlcat('https://api.example.com/', '/users')
→ 'https://api.example.com/users'
urlcat('http://example.com/', '/users/:userId/posts/:postId/comments', { userId: 123, postId: 987, authorId: 456, limit: 10, offset: 120 })
→ 'http://example.com/users/123/posts/987/comments?authorId=456&limit=10&offset=120'

query:构建查询字符串

使用指定的键值对构建查询字符串。键和值被转义,然后由 '&' 字符连接。

例如:

paramsresult
{}''
{ query: 'some text' }'query=some%20text'
{ id: 42, 'comment-id': 86 }'id=42&comment-id=86'
{ id: 42, 'a name': 'a value' }'id=42&a%20name=a%20value'

subst:替换路径参数

用模板字符串中的值替换参数。模板可能包含 0 个或多个参数占位符。占位符以冒号 (:) 开头,后跟只能包含大写或小写字母的参数名称。在模板中找到的任何占位符都将替换为 params 中相应键下的值。

例如:

templateparamsresult
':id'{ id: 42 }'42'
'/users/:id'{ id: 42 }'/users/42'
'/users/:id/comments/:commentId'{ id: 42, commentId: 86 }'/users/42/comments/86'
'/users/:id'{ id: 42, foo: 'bar' }'/users/42'

join:使用一个分隔符连接两个字符串

仅使用一个分隔符连接两个部分。如果分隔符出现在 part1 的末尾或 part2 的开头,则将其删除,然后使用分隔符连接两个部分。

例如:

part1separatorpart2result
'first'',''second''first,second'
'first,'',''second' 
'first'','',second' 
'first,'','',second' 

到此,相信大家对“JavaScript的库urlcat有什么作用”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI