Introduction to Node Fetch
Node-fetch is a lightweight module that allows you to make HTTP requests to servers using Promises. It is based on the Fetch API available in the browser, making it easier to use fetch requests within a Node.js environment. In this comprehensive guide, we will explore the various APIs provided by node-fetch and provide numerous code snippets to help you get started.
Basic Fetch Example
const fetch = require('node-fetch'); fetch('https://api.github.com') .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error('Error:', error));
Advanced Fetch with Options
const fetch = require('node-fetch'); const url = 'https://jsonplaceholder.typicode.com/posts'; const options = { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ title: 'foo', body: 'bar', userId: 1 }) }; fetch(url, options) .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error('Error:', error));
Fetching with Authorization
const fetch = require('node-fetch'); const url = 'https://api.github.com/user'; const options = { headers: { 'Authorization': 'Bearer YOUR_ACCESS_TOKEN' } }; fetch(url, options) .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error('Error:', error));
Handling Various Response Types
const fetch = require('node-fetch'); // Text response fetch('https://example.com') .then(response => response.text()) .then(data => console.log(data)) .catch(error => console.error('Error:', error)); // Buffer response fetch('https://example.com/image.png') .then(response => response.buffer()) .then(buffer => console.log(buffer)) .catch(error => console.error('Error:', error));
Using node-fetch in an Application
const fetch = require('node-fetch'); async function getGitHubUser(username) { try { const response = await fetch(`https://api.github.com/users/${username}`); const data = await response.json(); console.log(data); } catch (error) { console.error('Error:', error); } } getGitHubUser('octocat');
In this guide, we have covered the essential features of node-fetch, providing you with the knowledge to incorporate HTTP requests into your Node.js applications effortlessly. Whether you need to make a simple GET request or handle advanced scenarios with headers and authorization, node-fetch is a powerful tool to add to your development arsenal.
Hash: e497f5a5a076bdf3b2381a3bc11c5204339aac1f5819fb557800d3c0ad4ab14f