📜  axios xmlhttpReq - Javascript (1)

📅  最后修改于: 2023-12-03 14:39:26.099000             🧑  作者: Mango

Axios XMLHttpRequest - Javascript

Introduction

Axios is a Javascript library used for making HTTP requests from a browser or NodeJS. It is a lightweight library that provides an easy-to-use interface for making HTTP requests. Axios is widely used for its simplicity, robustness, and compatibility across different platforms.

Axios supports XMLHTTPRequest (XHR) requests by default, using the browser's built-in XMLHttpRequest API. It also supports Promise API, and it can be used on both the client and server-side.

Installation

The first step to using Axios XMLHttpRequest in your project is to install it. You can install it via NPM or Yarn:

npm install axios

Or

yarn add axios
Basic Usage

To use Axios in your project, you first need to create an instance of the Axios class. You can then use this instance to make HTTP requests to any API.

import axios from 'axios';

const instance = axios.create({
  baseURL: 'https://jsonplaceholder.typicode.com',
});

instance.get('/users')
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.log(error);
  });

In the above code, we are using Axios to make a GET request to an API hosted on https://jsonplaceholder.typicode.com. We are calling the get method of Axios and passing in the API endpoint /users. We are then using the Promise API to handle the response and error.

Interceptors

Axios also provides interceptors, which allow you to intercept requests and responses before they are handled by your application. You can use them to customize the behavior of your application.

import axios from 'axios';

const instance = axios.create({
  baseURL: 'https://jsonplaceholder.typicode.com',
});

instance.interceptors.request.use((config) => {
  console.log('Request Interceptor:', config);
  return config;
}, (error) => {
  console.log(error);
  return Promise.reject(error);
});

instance.interceptors.response.use((response) => {
  console.log('Response Interceptor:', response);
  return response;
}, (error) => {
  console.log(error);
  return Promise.reject(error);
});

instance.get('/users')
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.log(error);
  });

In the above code, we are intercepting requests and responses using Axios. We are using the use method to set up our interceptors. The request interceptor is called before the request is sent, and the response interceptor is called after the response is received.

Conclusion

Axios is a powerful library that simplifies HTTP requests in your applications. Whether you're using it for simple GET requests, or more complex requests with interceptors, Axios provides a simple, yet effective interface for handling HTTP requests. By following the basic usage and interceptors examples above, you'll be able to integrate Axios into your project and start making HTTP requests.