Skip to main content

Archive

Show more

Axios and HTTP Requests in React.js

Axios and HTTP Requests in React.js

Axios is a popular JavaScript library used for making HTTP requests from the browser. It provides an easy-to-use API for sending asynchronous HTTP requests to RESTful APIs and handling responses. In React.js applications, Axios is commonly used for fetching data from backend servers. Here's how to use Axios for HTTP requests in React.js:


1. Installation

To use Axios in your React.js project, you first need to install it via npm or yarn:

npm install axios

2. Making GET Requests

Use Axios to make GET requests to fetch data from a server:

Example:

import React, { useState, useEffect } from 'react';
import axios from 'axios';

const FetchData = () => {
  const [data, setData] = useState(null);

  useEffect(() => {
    axios.get('https://api.example.com/data')
      .then(response => setData(response.data))
      .catch(error => console.error('Error fetching data:', error));
  }, []);

  return (
    <div>
      {data ? (
        <div>
          <h2>Data:</h2>
          <pre>{JSON.stringify(data, null, 2)}</pre>
        </div>
      ) : (
        <p>Loading data...</p>
      )}
    </div>
  );
};

export default FetchData;

3. Making POST Requests

Use Axios to make POST requests to send data to a server:

Example:

import React, { useState } from 'react';
import axios from 'axios';

const PostData = () => {
  const [responseData, setResponseData] = useState(null);

  const postData = async () => {
    try {
      const response = await axios.post('https://api.example.com/data', { key: 'value' });
      setResponseData(response.data);
    } catch (error) {
      console.error('Error posting data:', error);
    }
  };

  return (
    <div>
      <button onClick={postData}>Post Data</button>
      {responseData && (
        <div>
          <h2>Response:</h2>
          <pre>{JSON.stringify(responseData, null, 2)}</pre>
        </div>
      )}
    </div>
  );
};

export default PostData;

4. Handling Errors

Axios provides error handling capabilities to handle HTTP errors gracefully:

Example:

axios.get('https://api.example.com/data')
  .then(response => {
    // Handle successful response
  })
  .catch(error => {
    console.error('Error:', error.response.status);
    // Handle error response
  });

5. Configuring Axios

Axios allows you to configure default settings such as base URL, headers, and request interceptors:

Example:

import axios from 'axios';

axios.defaults.baseURL = 'https://api.example.com';
axios.defaults.headers.common['Authorization'] = 'Bearer token';

6. Conclusion

Axios is a powerful library for making HTTP requests in React.js applications. With its intuitive API and robust error handling, Axios simplifies the process of fetching and sending data over HTTP. By following the examples provided above, you can effectively integrate Axios into your React.js projects for seamless communication with backend servers.

Comments