Sync Request Simplifying Synchronous HTTP Requests in Node.js

Introduction to Sync Request

The sync-request module in Node.js allows developers to perform synchronous HTTP requests. It simplifies the process of making HTTP calls by providing a straightforward API for sending GET, POST, PUT, and DELETE requests without using callback functions or Promises. This can be particularly useful in scripts where you need a blocking request.

Installation

npm install sync-request

Basic Usage

GET Request


const request = require('sync-request');
const res = request('GET', 'https://jsonplaceholder.typicode.com/posts/1');
console.log(res.getBody('utf8'));

POST Request


const request = require('sync-request');
const res = request('POST', 'https://jsonplaceholder.typicode.com/posts', {
    json: { title: 'foo', body: 'bar', userId: 1 }
});
console.log(res.getBody('utf8'));

PUT Request


const request = require('sync-request');
const res = request('PUT', 'https://jsonplaceholder.typicode.com/posts/1', {
    json: { id: 1, title: 'foo', body: 'bar', userId: 1 }
});
console.log(res.getBody('utf8'));

DELETE Request


const request = require('sync-request');
const res = request('DELETE', 'https://jsonplaceholder.typicode.com/posts/1');
console.log(res.getBody('utf8'));

Headers and Query Parameters


const request = require('sync-request');
const res = request('GET', 'https://jsonplaceholder.typicode.com/posts/1', {
    headers: {
        'Content-Type': 'application/json'
    },
    qs: { userId: 1 }
});
console.log(res.getBody('utf8'));

Error Handling


const request = require('sync-request');
try {
    const res = request('GET', 'https://jsonplaceholder.typicode.com/404');
    console.log(res.getBody('utf8'));
} catch (err) {
    console.error('Error:', err.message);
}

Application Example

Here’s an example of an application that uses the sync-request module to fetch data from an API and log it. This simplified script fetches a list of users, posts, and comments one after the other.


const request = require('sync-request');

function fetchUsers() {
  const res = request('GET', 'https://jsonplaceholder.typicode.com/users');
  return JSON.parse(res.getBody('utf8'));
}

function fetchPosts() {
  const res = request('GET', 'https://jsonplaceholder.typicode.com/posts');
  return JSON.parse(res.getBody('utf8'));
}

function fetchComments() {
  const res = request('GET', 'https://jsonplaceholder.typicode.com/comments');
  return JSON.parse(res.getBody('utf8'));
}

const users = fetchUsers();
console.log('Users:', users);

const posts = fetchPosts();
console.log('Posts:', posts);

const comments = fetchComments();
console.log('Comments:', comments);

The above application demonstrates how easy it is to make synchronous HTTP requests and process results sequentially using the sync-request module.

Hash: c10221e3e6dd46cc81f4749860c0b05197c55854b332c37ba0ab1985da3ac4eb

Leave a Reply

Your email address will not be published. Required fields are marked *