📜  javascript axios - Shell-Bash (1)

📅  最后修改于: 2023-12-03 15:31:36.775000             🧑  作者: Mango

JavaScript Axios

Axios is a popular promise-based HTTP client for JavaScript. It works on both the browser and Node.js platforms, making it a versatile tool for developers who need to make API calls.

Installation

You can install Axios using npm:

$ npm install axios

Or using yarn:

$ yarn add axios
Usage

To make a GET request, you can use the axios.get() method:

axios.get('https://jsonplaceholder.typicode.com/posts')
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.error(error);
  });

To make a POST request, you can use the axios.post() method:

axios.post('https://jsonplaceholder.typicode.com/posts', {
    title: 'foo',
    body: 'bar',
    userId: 1,
  })
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.error(error);
  });

You can also use Axios to send request with query parameters:

axios.get('https://jsonplaceholder.typicode.com/posts', {
    params: {
      userId: 1,
    },
  })
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.error(error);
  });
Interceptors

Axios also allows you to use interceptors to modify requests or responses before they are sent or received. For example, you can use an interceptor to add an authorization header to every request:

axios.interceptors.request.use(function(config) {
  const token = localStorage.getItem('authToken');

  if (token) {
    config.headers.Authorization = `Bearer ${token}`;
  }

  return config;
}, function(error) {
  return Promise.reject(error);
});
Conclusion

Axios is a powerful HTTP client for JavaScript that offers a simple, yet flexible interface. With its promise-based API and support for both browser and Node.js platforms, it's become a popular choice for developers working with APIs.