What is isomorphic-unfetch?
The isomorphic-unfetch npm package is a lightweight module that allows for making HTTP requests in both Node.js and browser environments. It's designed to provide a consistent API for fetch across these environments, making it easier to write isomorphic code that runs on both the server and the client.
Basic GET Request
This code sample demonstrates how to perform a basic GET request to retrieve data from an API and print it to the console. It uses the fetch API to make the request, parses the response as JSON, and handles any errors that may occur.
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
POST Request with JSON Body
This example shows how to send a POST request with a JSON body. It sets the method to POST, includes a Content-Type header to indicate the type of the request body, and uses JSON.stringify to convert a JavaScript object to a JSON string. The response is then parsed as JSON.
fetch('https://api.example.com/data', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
key: 'value'
}),
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));