Axios

Axios is a Promise-based HTTP client widely used for data scraping, API calls, and more. Axios supports setting up a proxy server through its built-in proxy configuration option. Please follow the steps below to configure a proxy (this tutorial applies to the Node.js environment)

lightbulb-exclamation-on


1

Install Axios

Axios can be installed via various package managers depending on your project environment. Please visit the Axios official documentationarrow-up-right for detailed installation instructions. For example, using npm:

npm install axios

2

Configure the Proxy

In your code, you need to create a configuration object containing the proxy information. Replace the placeholders in the template below with your actual credentials:

const proxyConfig = {
  host: 'your-proxy-host',  
  port: your-proxy-port,       
  protocol: 'http',       
  auth: {
    username: 'your-username', 
    password: 'your-password'
  }
};      

3

Use the Proxy in a Request

Below is a complete example that sends a request to ipinfo.io (which returns the IP information of the request origin) using the configured proxy. Save this code in a file, for example test-proxy.js.

const axios = require('axios');

// Your target URL, here we use http://ipinfo.io/
const targetUrl = 'http://ipinfo.io/';

const proxyConfig = {
  host: 'your-proxy-host',
  port: your-proxy-port,
  protocol: 'http',
  auth: {
    username: 'your-username',
    password: 'your-password'
  }
};

async function fetchData() {
  try {
    // Pass proxyConfig as an option to axios.get
    const response = await axios.get(targetUrl, { proxy: proxyConfig });
    console.log('Success:', response.data);
  } catch (error) {
    console.error('Fail:', error.message);
  }
}

fetchData();

4

Verify the Proxy

In your terminal, navigate to the directory containing your JavaScript file (e.g., test-proxy.js) and run the following command (replace test-proxy.js with your actual filename if different):

node test-proxy.js

If the proxy is configured correctly, you should see output similar to the following:

Success: {
  ip: '203.0.113.45',
  city: 'Houston',
  region: 'Texas',
  country: 'US',
  loc: '29.7633,-95.3633',
  org: 'AS174 Cogent Communications, LLC',
  postal: '77002',
  timezone: 'America/Chicago',
  readme: 'https://ipinfo.io/missingauth'
}


Last updated