Topics HTTP & Networking Making HTTP Requests
intermediate 15 min read

Making HTTP Requests

Fetch data from external APIs using http/https module and popular libraries.

HTTP Client

const https = require('https');\n\nhttps.get('https://api.github.com/users/octocat', { headers: { 'User-Agent': 'Node' } }, (res) => {\n  let data = '';\n  res.on('data', chunk => data += chunk);\n  res.on('end', () => {\n    console.log(JSON.parse(data).login);\n  });\n});

Using node-fetch

import fetch from 'node-fetch';\n\nconst response = await fetch('https://api.example.com/users', {\n  method: 'POST',\n  headers: { 'Content-Type': 'application/json' },\n  body: JSON.stringify({ name: 'Alice', email: '[email protected]' }),\n});\n\nconst data = await response.json();\nconsole.log(data);

Using Axios

const axios = require('axios');\n\nconst { data } = await axios.get('/api/users', {\n  params: { page: 1, limit: 10 },\n});\n\nconsole.log(data);

Examples

const https = require('https');

function fetchJson(url) {
  return new Promise((resolve, reject) => {
    https.get(url, { headers: { 'User-Agent': 'Node' } }, (res) => {
      let body = '';
      res.on('data', chunk => body += chunk);
      res.on('end', () => {
        try {
          resolve(JSON.parse(body));
        } catch (e) {
          reject(e);
        }
      });
    }).on('error', reject);
  });
}

// Usage
fetchJson('https://jsonplaceholder.typicode.com/todos/1')
  .then(data => console.log('Todo:', data.title))
  .catch(err => console.error('Error:', err.message));

Your Notes

Sign in to take notes for this lesson.

Discussion

Sign in to join the discussion.

Flashcards

Sign in to create flashcards.