跳至内容

获取

WHATWG fetch() 的同构现代/遗留/Node polyfill。

此包替换用于 HTTP 调用的http包。fetch包为WHATWG fetch 规范提供 polyfill,用于遗留浏览器或默认为现代浏览器和 Node 中可用的全局类。建议您使用此包以确保与非现代浏览器的兼容性。

有关更多信息,我们建议您阅读 MDN 文章,因为本文仅介绍了在 Meteor 中的基本用法。

用法

安装

要将此包添加到现有应用程序中,请从您的应用程序目录运行以下命令

bash
meteor add fetch

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

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

API

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

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

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

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 });