When sending HTTP requests with Axios, it is sometimes necessary to include the Authorization header in the request to ensure that requests to the server are authorized. The Authorization header is typically used to pass tokens (e.g., JWT) or basic authentication credentials.
The following are the steps to add the Authorization header in Axios:
1. Installing and Importing Axios
First, ensure that Axios is installed in your project. If not installed, you can install it via npm or yarn:
bashnpm install axios
Then, import Axios in your file:
javascriptimport axios from 'axios';
2. Setting the Request's Authorization Header
You can add the Authorization header directly in the request configuration or set it globally using Axios.
Example 1: Adding the Authorization Header in a Single Request
javascriptaxios.get('https://api.example.com/data', { headers: { 'Authorization': `Bearer YOUR_ACCESS_TOKEN` } }) .then(response => { console.log(response.data); }) .catch(error => { console.error('Error:', error); });
In this example, we send a GET request to https://api.example.com/data and include an Authorization header with the value Bearer YOUR_ACCESS_TOKEN.
Example 2: Global Configuration for Authorization Header
If multiple requests require the same Authorization header, you can set it globally:
javascriptaxios.defaults.headers.common['Authorization'] = `Bearer YOUR_ACCESS_TOKEN`;
After this setup, all requests sent using Axios will automatically include this Authorization header.
3. Using an Axios Instance
For better management and reusability of configurations, create an Axios instance and configure it:
javascriptconst apiClient = axios.create({ baseURL: 'https://api.example.com', headers: { 'Authorization': `Bearer YOUR_ACCESS_TOKEN` } }); apiClient.get('/data') .then(response => console.log(response.data)) .catch(error => console.error('Error:', error));
This approach helps control different request configurations effectively and makes the code more modular.
Summary
By configuring the Authorization header, Axios can securely send requests to servers requiring authentication. This applies not only to Bearer tokens but also to other authentication schemes. Using the methods above, you can flexibly configure the required headers for different requests or globally.