DEV Community

Ali Sherief
Ali Sherief

Posted on

The new way to make GET and POST requests (Node)

Request was deprecated in February 2020. Being a widely used HTTP request library and dependency of almost every Node module, including npm itself, it is necessary to find an alternative module that has the same capabilities of Request.

Enter node-fetch. It allows you to use the window.fetch() Javascript function to make HTTP calls. Unlike Request, it also returns a Promise object. If you've used JS long enough you probably find it easier to chain Promise objects instead of managing asynchronous function callbacks.

So without further ado, let's begin. But make sure you install node-fetch first, npm i node-fetch.

GET request

You can call fetch() with just the URL to perform a GET request.

const fetch = require("node-fetch");

const f = async url => {
    const response = await fetch('https://api.github.com/users/github')
    // Let's assume that this request returns a JSON response
    const json = await response.json();
}Z
Enter fullscreen mode Exit fullscreen mode

fetch() returns a Promise. You should await it to wait for the Promise to resolve, because if you use it immediately you will only have the bare Promise object. Obviously you can only do this inside an async function.

This also works:

const fetch = require('node-fetch');

fetch('https://api.github.com/users/github')
    .then(res => res.json())
    .then(json => console.log(json));
Enter fullscreen mode Exit fullscreen mode

Instead of using async and await you can use then() to wait for the Promise to resolve, and it works everywhere.

And to put query parameters at the end you build a URLSearchParams object and concatenate it with the URL string like this:

const fetch = require('node-fetch');

const url = 'https://api.github.com/users/github'
const params = new URLSearchParams({ foo: 'BAR' })
fetch(url + params).then(console.log)
Enter fullscreen mode Exit fullscreen mode

POST request

Here I will also cover different types of data that can be sent.

Simple POST with application/x-www-form-encoded content type, the default if a content type is not passed in the header:

const fetch = require('node-fetch');

fetch('https://httpbin.org/post', {method: 'POST', body: 'a=1'})
    .then(res => res.json()) // expecting a json response
    .then(json => console.log(json));
Enter fullscreen mode Exit fullscreen mode

And this is a POST with a content type of application/json:

const fetch = require('node-fetch');

const body = {a: 1};

fetch('https://httpbin.org/post', {
    method: 'post',
    body: JSON.stringify(body),
    headers: {'Content-Type': 'application/json'}
})
    .then(res => res.json())
    .then(json => console.log(json));
Enter fullscreen mode Exit fullscreen mode

To make a POST of type multipart/form-data, you need to do a little extra work. Install the form-data npm package and then build a FormData object like this:

const fetch = require('node-fetch');
const FormData = require('form-data');

const url = 'https://example.com/post'

const form = new FormData();
form.append("foo", "bar");
form.append("baz", "quux");

fetch(url, {
    method: "POST",
    body: form
}).then(r => return r.json())
.then(json => console.log(json));
Enter fullscreen mode Exit fullscreen mode

And we're done

If you found any errors in this post please let me know so I can correct them.

Top comments (2)

Collapse
 
spez profile image
Abhigyan • Edited

Help

The fetch package is amazing but you cannot assign the response to a global variable outside the weird asynchronous thing. And if we can, how?🤔🤔🤔

Collapse
 
itachiuchiha profile image
Itachi Uchiha

You can also get json responses like that;

await (await fetch('https://apiurl.com/someendpoint')).json()