Introduction to Server Requests in JavaScript

Server requests in JavaScript are fundamental for interacting with servers. They allow you to: retrieve data (GET), send data (POST), update data (PUT/PATCH), and remove data (DELETE).

Three primary ways you make server requests in JavaScript are: Fetch API, XMLHttpRequest (XHR), and Node.js HTTP libraries.

Fetch API

1. GET Request

Fetching (retrieving) data from a server.

fetch('https://api.example.com/data')
    .then(response => response.json())
    .then(data => console.log(data))
    .catch(error => console.error('Error:', error));

2. POST Request

Sending data to the server.

fetch('https://api.example.com/data', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
    },
    body: JSON.stringify({ name: 'John', age: 30 }),
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));

3. PUT Request

Updating an existing resource.

fetch('https://api.example.com/data/1', {
    method: 'PUT',
    headers: {
        'Content-Type': 'application/json',
    },
    body: JSON.stringify({ name: 'John Updated', age: 31 }),
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));

4. DELETE Request

Deleting a resource.

fetch('https://api.example.com/data/1', {
    method: 'DELETE'
})
.then(response => response.json())
.then(data => console.log('Deleted', data))
.catch(error => console.error('Error:', error));

XMLHttpRequest (XHR)

1. GET Request

Old school way to retrieve data.

var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.example.com/data', true);
xhr.onload = function() {
    if (xhr.status >= 200 && xhr.status < 300) {
        console.log(JSON.parse(xhr.responseText));
    } else {
        console.error('Request failed!');
    }
};
xhr.onerror = function() {
    console.error('Network error!');
};
xhr.send();

2. POST Request

Sending data using XHR.

var xhr = new XMLHttpRequest();
xhr.open('POST', 'https://api.example.com/data', true);
xhr.setRequestHeader('Content-Type', 'application/json;charset=UTF-8');
xhr.onload = function() {
    if (xhr.status >= 200 && xhr.status < 300) {
        console.log(JSON.parse(xhr.responseText));
    } else {
        console.error('Request failed!');
    }
};
xhr.onerror = function() {
    console.error('Network error!');
};
xhr.send(JSON.stringify({ name: 'John', age: 30 }));

3. PUT Request

Updating data with XHR.

var xhr = new XMLHttpRequest();
xhr.open('PUT', 'https://api.example.com/data/1', true);
xhr.setRequestHeader('Content-Type', 'application/json;charset=UTF-8');
xhr.onload = function() {
    if (xhr.status >= 200 && xhr.status < 300) {
        console.log('Updated:', JSON.parse(xhr.responseText));
    } else {
        console.error('Request failed!');
    }
};
xhr.onerror = function() {
    console.error('Network error!');
};
xhr.send(JSON.stringify({ name: 'Updated John', age: 32 }));

4. DELETE Request

Removing data.

var xhr = new XMLHttpRequest();
xhr.open('DELETE', 'https://api.example.com/data/1', true);
xhr.onload = function() {
    if (xhr.status >= 200 && xhr.status < 300) {
        console.log('Deleted:', JSON.parse(xhr.responseText));
    } else {
        console.error('Request failed!');
    }
};
xhr.onerror = function() {
    console.error('Network error!');
};
xhr.send();

Node.js (HTTP Requests)

1. Using node-fetch (Recommended)

In Node.js, you can use node-fetch (similar to browser fetch).

// First install: npm install node-fetch
import fetch from 'node-fetch';

fetch('https://api.example.com/data')
    .then(response => response.json())
    .then(data => console.log(data))
    .catch(error => console.error('Error:', error));

2. Using http Core Module (Native Node.js)

Native HTTP request using built-in modules.

const http = require('http');

const options = {
    hostname: 'api.example.com',
    path: '/data',
    method: 'GET',
};

const req = http.request(options, res => {
    let data = '';
    res.on('data', chunk => {
        data += chunk;
    });
    res.on('end', () => {
        console.log(JSON.parse(data));
    });
});

req.on('error', error => {
    console.error(error);
});

req.end();

3. Using axios (Popular Alternative)

Axios is an easier and very popular choice.

// First install: npm install axios
import axios from 'axios';

// GET Request
axios.get('https://api.example.com/data')
    .then(response => console.log(response.data))
    .catch(error => console.error(error));

// POST Request
axios.post('https://api.example.com/data', {
    name: 'John',
    age: 30
})
.then(response => console.log(response.data))
.catch(error => console.error(error));

Summary of HTTP Methods