13: مكتبة axios في الجافاسكريبت | axios in javascript

3 min read 12 days ago
Published on Aug 22, 2025 This response is partially generated with the help of AI. It may contain inaccuracies.

Table of Contents

Introduction

This tutorial covers how to use Axios, a popular JavaScript library for making HTTP requests. Axios simplifies the process of sending asynchronous requests to servers and handling responses, making it a valuable tool for web developers. This guide will walk you through the installation, basic usage, and some advanced features of Axios.

Step 1: Install Axios

To begin using Axios in your project, you need to install it. You can do this via npm (Node Package Manager). Follow these steps:

  1. Open your terminal or command prompt.
  2. Navigate to your project directory.
  3. Run the following command:
    npm install axios
    

Step 2: Import Axios into Your Project

Once Axios is installed, you need to import it into your JavaScript file. Here’s how:

  • For ES6 modules, use:
    import axios from 'axios';
    
  • For CommonJS, use:
    const axios = require('axios');
    

Step 3: Making a GET Request

To retrieve data from a server, you can use a GET request. Here’s a simple example:

  1. Use the following code to make a GET request:

    axios.get('https://api.example.com/data')
      .then(response => {
        console.log(response.data);
      })
      .catch(error => {
        console.error('Error fetching data:', error);
      });
    
  2. Replace 'https://api.example.com/data' with the actual URL from which you want to fetch data.

Step 4: Making a POST Request

To send data to a server, use a POST request. Follow these steps:

  1. Create a POST request with the following code:

    axios.post('https://api.example.com/data', {
        name: 'John Doe',
        age: 30
    })
    .then(response => {
        console.log('Data submitted:', response.data);
    })
    .catch(error => {
        console.error('Error submitting data:', error);
    });
    
  2. Modify the URL and the data object to match your requirements.

Step 5: Handling Responses

Axios responses are returned as promises, and you can access the response data easily. Key points to remember include:

  • Use .then() to handle successful responses.
  • Use .catch() to handle errors.
  • Access data via response.data.

Step 6: Setting Up Axios Defaults

To avoid repeating configuration in each request, you can set defaults for Axios. Here’s how:

  1. Set default base URL:

    axios.defaults.baseURL = 'https://api.example.com';
    
  2. Set default headers:

    axios.defaults.headers.common['Authorization'] = 'Bearer yourToken';
    

Step 7: Canceling Requests

If you need to cancel a request, Axios provides a way to do that. Here’s an example:

  1. Create a cancel token:
    const CancelToken = axios.CancelToken;
    let cancel;
    
    axios.get('https://api.example.com/data', {
        cancelToken: new CancelToken(function executor(c) {
            cancel = c;
        })
    }).catch(function (thrown) {
        if (axios.isCancel(thrown)) {
            console.log('Request canceled', thrown.message);
        } else {
            // Handle error
        }
    });
    
    // To cancel the request
    cancel('Operation canceled by the user.');
    

Conclusion

In this tutorial, you learned how to install and use the Axios library for making HTTP requests in JavaScript. Key takeaways include making GET and POST requests, handling responses, setting up defaults, and canceling requests. As a next step, consider exploring additional Axios features, such as interceptors and request/response transformation, to enhance your web applications. Feel free to reach out with questions or join the community for further discussions.