13: مكتبة axios في الجافاسكريبت | axios in javascript
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:
- Open your terminal or command prompt.
- Navigate to your project directory.
- 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:
-
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); });
-
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:
-
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); });
-
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:
-
Set default base URL:
axios.defaults.baseURL = 'https://api.example.com';
-
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:
- 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.