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.
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));
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));
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));
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));
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();
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 }));
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 }));
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-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));
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();
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));