Introduction to isomorphic-fetch
isomorphic-fetch is a popular library that allows you to make HTTP requests in both Node.js and browser environments. This capability makes it ‘isomorphic’, meaning the same code can run on both server and client sides.
Getting Started
First, you need to install the isomorphic-fetch
and es6-promise
polyfill for it to work across different environments.
npm install isomorphic-fetch es6-promise
Basic Usage
Here is a simple fetch example to get you started:
import fetch from 'isomorphic-fetch';
fetch('https://api.github.com/users/github')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
Advanced Usage
Let’s dive into some advanced use cases:
POST Request with JSON Body
import fetch from 'isomorphic-fetch';
fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
title: 'foo',
body: 'bar',
userId: 1
})
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
Handling HTTP Headers
import fetch from 'isomorphic-fetch';
fetch('https://jsonplaceholder.typicode.com/posts/1')
.then(response => {
console.log(response.headers.get('Content-Type'));
return response.json();
})
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
Using with Async/Await
import fetch from 'isomorphic-fetch';
async function getUser() {
try {
const response = await fetch('https://api.github.com/users/github');
const data = await response.json();
console.log(data);
} catch (error) {
console.error('Error:', error);
}
}
getUser();
App Example
Here’s a simple app example utilizing the introduced APIs:
import express from 'express';
import fetch from 'isomorphic-fetch';
const app = express();
const port = 3000;
app.get('/users', async (req, res) => {
try {
const response = await fetch('https://api.github.com/users');
const data = await response.json();
res.json(data);
} catch (error) {
res.status(500).json({ error: 'Failed to fetch users' });
}
});
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});
By following this guide, you should be able to use isomorphic-fetch
to make HTTP requests efficiently in both Node.js and browser environments.
Hash: 007b33309199af3fed09330d99b3b1b51d8fd4e5ddc162ff20d382c6c1d33490