node-fetch examples for GET, POST, JSON , File Upload

In this article, I have provided node-fetch examples  for GET & POST methods. In the ever-evolving world of web development, mastering HTTP requests is a fundamental skill. Today, we’re focusing on node-fetch, a lightweight module in Node.js, which brings the familiar Fetch API to the server side. This versatile library allows you to make various types of requests, such as GET, POST, handling JSON bodies, and even uploading files. Let’s explore how node-fetch can be used in different scenarios.

 

GET Request Example

GET requests are arguably the most common type of HTTP request. They are used primarily for retrieving data from a server. In Node.js, using node-fetch to make a GET request is straightforward and mirrors the simplicity of the browser Fetch API. When making a GET request, node-fetch sends a request to the server and retrieves the data, which can be in various formats such as JSON, XML, or plain text.

function fetchGetExample() {
  const fetch = require('node-fetch');
  fetch('https://jsonplaceholder.typicode.com/posts/1')
    .then(response => response.json())
    .then(data => console.log(data));
}

fetchGetExample();

Output:

{
  "userId": 1,
  "id": 1,
  "title": "Example title",
  "body": "Example body text..."
}

 

POST Request Example

POST requests are essential when the goal is to send data to the server, often for updating it or creating new resources. With node-fetch, making a POST request involves specifying the method and body of the request. This body can be a string, a buffer, a form, or even a stream, depending on the requirements of the API you’re working with.

function fetchPostExample() {
  const fetch = require('node-fetch');
  const url = 'https://httpbin.org/post';
  const options = {
    method: 'POST',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
    },
    body: 'foo=bar&hello=world'
  };
  
  fetch(url, options)
    .then(response => response.json())
    .then(data => console.log(data));
}

fetchPostExample();

Output:

{
  "args": {},
  "data": "",
  "files": {},
  "form": {
    "foo": "bar",
    "hello": "world"
  },
  "headers": {
    ...
  },
  "json": null,
  "origin": "..."
}

 

POST Request with JSON Body

JSON has become the de facto standard for data exchange in web APIs. node-fetch simplifies the process of sending and receiving JSON data. When dealing with JSON, it’s crucial to set the correct headers and stringify the JSON body when sending a request. Similarly, when receiving a JSON response, node-fetch allows for easy parsing to convert the JSON string back into a JavaScript object.When dealing with JSON data, ensure your POST request’s Content-Type is set to application/json. The JSON data should be stringified before sending:

function fetchPostJsonExample() {
  const fetch = require('node-fetch');
  const url = 'https://httpbin.org/post';
  const data = {
    title: 'foo',
    body: 'bar',
    userId: 1
  };
  const options = {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(data)
  };
  
  fetch(url, options)
    .then(response => response.json())
    .then(data => console.log(data));
}

fetchPostJsonExample();

Output:

{
  "args": {},
  "data": "{\"title\":\"foo\",\"body\":\"bar\",\"userId\":1}",
  "files": {},
  "form": {},
  "headers": {
    ...
  },
  "json": {
    "title": "foo",
    "body": "bar",
    "userId": 1
  },
  "origin": "..."
}

 

File Upload Example

Uploading files might seem daunting, but node-fetch makes this process more accessible. Handling file uploads involves creating a FormData object, appending the files you wish to upload, and then sending this form as the body of your POST request. This is particularly useful for applications that require user-generated content, such as images or documents.

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

function fetchFileUploadExample() {
  const url = 'https://httpbin.org/post';
  const form = new FormData();
  const fileStream = fs.createReadStream('path/to/your/file.jpg');
  
  form.append('file', fileStream);

  const options = {
    method: 'POST',
    body: form
  };

  fetch(url, options)
    .then(response => response.json())
    .then(data => console.log(data));
}

fetchFileUploadExample();

Output:

{
  "args": {},
  "data": "",
  "files": {
    "file": "data:image/jpeg;base64,..."
  },
  "form": {},
  "headers": {
    ...
  },
  "json": null,
  "origin": "..."
}

 

Conclusive Summary

Using node-fetch in Node.js allows you to perform various HTTP requests such as GET, POST, sending JSON data, and file upload with ease. The examples provided demonstrate the different types of requests and their usage. Begin integrating these examples into your applications to interact with APIs smoothly.

References