From 43b09fc2f6c37374d620d3cd4eda91fefc0d8675 Mon Sep 17 00:00:00 2001 From: Gabriel Grubba <70247653+Grubba27@users.noreply.github.com> Date: Thu, 25 Jan 2024 16:15:58 -0300 Subject: [PATCH] docs-packages: fetch --- v3-docs/docs/packages/fetch.md | 69 ++++++++++++++++++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100644 v3-docs/docs/packages/fetch.md diff --git a/v3-docs/docs/packages/fetch.md b/v3-docs/docs/packages/fetch.md new file mode 100644 index 0000000000..e7385334cd --- /dev/null +++ b/v3-docs/docs/packages/fetch.md @@ -0,0 +1,69 @@ +# Fetch + +Isomorphic modern/legacy/Node polyfill for WHATWG fetch(). + +This package replaces the `http` package for HTTP calls. `fetch` package provides polyfill for the [WHATWG fetch specification](https://fetch.spec.whatwg.org/) 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. + +For more information we recommend [reading the MDN articles](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) 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 +``` + +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 + +You can import `fetch`, `Headers`, `Request` and `Response` classes from `meteor/fetch`. + +```js +import { fetch, Headers, Request, Response } from "meteor/fetch"; +``` + +For the most part though, you will only need to import `fetch` and `Headers`. + +```js +import { Meteor } from 'meteor/meteor'; +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 postDataCall = Meteor.wrapAsync(postData); +const results = postDataCall('https://www.example.org/statsSubmission', { totalUsers: 55 })); + +```