Skip to content

URL

url 包为旧版浏览器的 WHATWG url 规范 提供 polyfill,或默认为现代浏览器和 Node 中可用的全局类。建议你使用此软件包与非现代浏览器兼容。

¥url package provides polyfill for the WHATWG url specification for legacy browsers or defaults to the global class which is available in modern browsers and Node. It is recommended that you use this package for compatibility with non-modern browsers.

有关更多信息,我们建议阅读 阅读 MDN 文章,并查看 Node API 文档 以了解更多详细信息,因为本文仅涵盖 Meteor 中的基本用法。

¥For more information we recommend reading the MDN articles about it and looking over the Node API documentation for more details as this article covers only basic usage in Meteor.

用法

¥Usage

安装

¥Installation

要将此包添加到现有应用,请从你的应用目录运行以下命令:

¥To add this package to an existing app, run the following command from your app directory:

bash
meteor add url

要将 url 包添加到现有包,请在你的 package.js 文件中的 Package.onUse 回调中包含语句 api.use('url');

¥To add the url package to an existing package, include the statement api.use('url'); in the Package.onUse callback in your package.js file:

js
Package.onUse((api) => {
  api.use("url");
});

安装包后,你可以从包中导入 URLURLSearchParams,并按照 MDN 和 Node 文档中的说明使用它。

¥After installing the package you can then import the URL and URLSearchParams from the package and use it as described at MDN and Node documentations.

URL

js
import { URL } from "meteor/url";

const url = new URL("https://www.meteor.com");

然后,你可以在 fetch 调用中使用 URL

¥You can then use URL for example in a fetch call:

js
import { URL } from 'meteor/url';
import { fetch } from 'meteor/fetch';

const url = new URL('https://www.example.com/api/reportVisit');

fetch(url, {
    method: 'POST',
    body: JSON.stringify({ siteId: 11 })
    ...
})

URLSearchParams

js
import { URLSearchParams } from "meteor/url";

const searchParams = new URLSearchParams({ query: "WHATWG", location: "MDN" });

然后,如果你在创建 URL 类时单独构建它们,则可以将 URLSearchParams 包含在 URL 的选项中。

¥You can then include URLSearchParams in the options for URL if you build them separately from when creating the URL class.