Skip to main content

Using Fetch

Introduction

Sapphire's fetch package, @sapphire/fetch is a small wrapper around cross-fetch so it will work in both the web browser and the native node.js environment.

Installation

npm install @sapphire/fetch

Usage

GETting JSON data
// Import the fetch function
const { fetch, FetchResultTypes } = require('@sapphire/fetch');

// Fetch the data. No need to call `.json()` after making the request!
const data = await fetch('https://jsonplaceholder.typicode.com/todos/1', FetchResultTypes.JSON);

// Do something with the data
console.log(data.userId);
GETting Buffer data
// Import the fetch function
const { fetch, FetchResultTypes } = require('@sapphire/fetch');

// Fetch the data. No need to call `.buffer()` after making the request!
const sapphireLogo = await fetch('https://github.com/sapphiredev.png', FetchResultTypes.Buffer);

// sapphireLogo is the `Buffer` of the image
console.log(sapphireLogo);
POSTing JSON data
// Import the fetch function
const { fetch, FetchResultTypes, FetchMethods } = require('@sapphire/fetch');

// Fetch the data. No need to call `.json()` after making the request!
const responseData = await fetch(
'https://jsonplaceholder.typicode.com/todos',
{
method: FetchMethods.Post,
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
name: 'John Doe'
})
},
FetchResultTypes.JSON
);

// Do something with the response data
console.log(responseData);