Skip to content

获取

¥Fetch

WHATWG fetch() 的同构现代/旧版/Node polyfill。

¥Isomorphic modern/legacy/Node polyfill for WHATWG fetch().

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

¥This package replaces the http package for HTTP calls. fetch package provides polyfill for the WHATWG fetch 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 文章,因为本文仅涵盖 Meteor 中的基本用法。

¥For more information we recommend reading the MDN articles about it 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 fetch

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

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

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

API

你可以从 meteor/fetch 导入 fetchHeadersRequestResponse 类。

¥You can import fetch, Headers, Request and Response classes from meteor/fetch.

js
import { fetch, Headers, Request, Response } from "meteor/fetch";

不过,在大多数情况下,你只需要导入 fetchHeaders

¥For the most part though, you will only need to import fetch and Headers.

js
import { fetch, Headers } from 'meteor/fetch';

async function postData (url, data) {
    try {
      const response = await fetch(url, {
          method: 'POST', // *GET, POST, PUT, DELETE, etc.
          mode: 'cors', // no-cors, *cors, same-origin
          cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
          credentials: 'same-origin', // include, *same-origin, omit
          headers: new Headers({
              Authorization: 'Bearer my-secret-key',
              'Content-Type': 'application/json'
          }),
          redirect: 'follow', // manual, *follow, error
          referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
          body: JSON.stringify(data) // body data type must match "Content-Type" header
      });
      const data = await response.json();
      return response(null, data);
    } catch (err) {
      return response(err, null);
    }
}

const result = await postData('https://www.example.org/statsSubmission', { totalUsers: 55 });