JAVASCRIPT

Make Server-Side API Calls with Axios in Node.js

Perform robust server-to-server API integrations in Node.js using Axios, including comprehensive error handling for network issues and API responses.

const axios = require('axios'); // Ensure axios is installed: npm install axios

async function callExternalApiServerSide(url, method = 'GET', data = null, headers = {}) {
  try {
    const response = await axios({
      method,
      url,
      data, // For POST, PUT, DELETE
      headers: {
        'Content-Type': 'application/json',
        ...headers
      }
    });
    console.log('Server-side API response:', response.data);
    return response.data;
  } catch (error) {
    if (axios.isAxiosError(error)) {
      // Handle API errors (e.g., 4xx, 5xx responses)
      console.error('Axios API Error:', error.response ? error.response.data : error.message);
      throw new Error(error.response ? JSON.stringify(error.response.data) : error.message);
    } else {
      // Handle other errors (e.g., network issues)
      console.error('Network or unexpected error:', error.message);
      throw error;
    }
  }
}

// Example usage:
// (async () => {
//   try {
//     const users = await callExternalApiServerSide('https://jsonplaceholder.typicode.com/users');
//     console.log('Fetched users:', users[0].name);
//
//     const newUser = { name: 'John Doe', username: 'johndoe' };
//     const createdUser = await callExternalApiServerSide('https://jsonplaceholder.typicode.com/users', 'POST', newUser);
//     console.log('Created user:', createdUser);
//   } catch (error) {
//     console.error('Server-side API call failed:', error);
//   }
// })();
How it works: This Node.js snippet demonstrates how to make server-to-server API calls using the popular `axios` library. It includes robust error handling for both HTTP response errors (e.g., 404, 500) and network issues. This approach is ideal for backend services that need to integrate with external APIs securely and reliably, without exposing tokens or logic to the client.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs