Introduction to isomorphic-fetch
isomorphic-fetch is a versatile library that enables fetching resources in a universal manner, compatible both with client-side and server-side JavaScript environments. It acts as a wrapper around the whatwg-fetch
polyfill and Node.js fetch
API.
Installation
npm install isomorphic-fetch --save
Basic Usage
import fetch from 'isomorphic-fetch';
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data));
API Examples
GET Request
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
POST Request
fetch('https://api.example.com/data', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
key1: 'value1',
key2: 'value2'
})
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
PUT Request
fetch('https://api.example.com/data/1', {
method: 'PUT',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
key1: 'newValue1',
key2: 'newValue2'
})
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
DELETE Request
fetch('https://api.example.com/data/1', {
method: 'DELETE'
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
Handling Headers
fetch('https://api.example.com/data', {
headers: {
'Authorization': 'Bearer your-token',
'Content-Type': 'application/json'
}
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
App Example
Here is a simple app example using isomorphic-fetch
to fetch user data:
import fetch from 'isomorphic-fetch';
class UserDataApp extends React.Component {
state = { users: [] };
componentDidMount() {
fetch('https://api.example.com/users')
.then(response => response.json())
.then(users => this.setState({ users }))
.catch(error => console.error('Error fetching users:', error));
}
render() {
const { users } = this.state;
return (
User Data
{users.map(user => (
- {user.name}
))}
);
}
}
export default UserDataApp;
By integrating isomorphic-fetch
into your applications, you gain the power to make network requests in a consistent and versatile way, regardless of the environment.