0
0
NodejsHow-ToBeginner · 4 min read

How to Use Axios in Node.js: Simple HTTP Requests Guide

To use axios in Node.js, first install it with npm install axios. Then, import it using import axios from 'axios' or const axios = require('axios') and call methods like axios.get() to make HTTP requests.
📐

Syntax

The basic syntax to use axios involves importing the library and calling its HTTP methods like get, post, put, or delete. Each method returns a promise that resolves with the response.

  • Import axios: Use import axios from 'axios' (ESM) or const axios = require('axios') (CommonJS).
  • Make request: Call axios.get(url) or other methods with the URL and optional config.
  • Handle response: Use await or .then() to get the response data.
javascript
import axios from 'axios';

async function fetchData() {
  try {
    const response = await axios.get('https://api.example.com/data');
    console.log(response.data);
  } catch (error) {
    console.error(error);
  }
}
💻

Example

This example shows how to make a GET request to a public API using axios in Node.js. It prints the JSON response data or an error if the request fails.

javascript
import axios from 'axios';

async function getUser() {
  try {
    const response = await axios.get('https://jsonplaceholder.typicode.com/users/1');
    console.log('User name:', response.data.name);
  } catch (error) {
    console.error('Error fetching user:', error.message);
  }
}

getUser();
Output
User name: Leanne Graham
⚠️

Common Pitfalls

Common mistakes when using axios in Node.js include:

  • Not installing axios before importing it.
  • Using require in ESM modules or import in CommonJS without proper setup.
  • Forgetting to handle errors with try/catch or .catch().
  • Not awaiting the promise, causing unexpected behavior.
javascript
/* Wrong: Missing await, no error handling */
import axios from 'axios';

function fetchData() {
  const response = axios.get('https://jsonplaceholder.typicode.com/posts/1');
  response.then(res => console.log(res.data)); // Correctly handle promise
}

fetchData();

/* Right: Await and try/catch */
async function fetchDataCorrect() {
  try {
    const response = await axios.get('https://jsonplaceholder.typicode.com/posts/1');
    console.log(response.data);
  } catch (error) {
    console.error(error);
  }
}

fetchDataCorrect();
📊

Quick Reference

Here is a quick summary of common axios methods and usage tips:

MethodDescriptionExample
axios.get(url)Fetch data from the URLawait axios.get('https://api.com')
axios.post(url, data)Send data to the URLawait axios.post('https://api.com', {name: 'John'})
axios.put(url, data)Update data at the URLawait axios.put('https://api.com/1', {name: 'Jane'})
axios.delete(url)Delete resource at the URLawait axios.delete('https://api.com/1')
Error handlingUse try/catch or .catch()try { await axios.get(url) } catch (e) { }

Key Takeaways

Install axios with npm before using it in Node.js.
Import axios properly depending on your module system (ESM or CommonJS).
Use async/await with try/catch to handle HTTP requests and errors cleanly.
Axios methods return promises that resolve with the response object.
Always handle errors to avoid unhandled promise rejections.