When using Axios for HTTP requests, you may need to set custom request headers. In Axios, setting request headers can be configured globally or for individual requests. Here are the two most common methods.
Setting Request Headers in Axios - Individual Requests
For individual requests, you can directly add the headers property to the request configuration object to specify the required headers. Here is a simple example showing how to add custom headers to a GET request:
javascriptaxios.get('/user', { headers: { 'Authorization': 'Bearer YOUR_TOKEN', 'Content-Type': 'application/json' } }) .then(response => { console.log(response.data); }) .catch(error => { console.log(error); });
In this example, we send a GET request with custom Authorization and Content-Type headers. Of course, you can set any other headers as needed.
Setting Request Headers in Axios - Global Default Values
If you want to set common headers for all requests, you can use Axios's global defaults. This can be achieved by modifying Axios's defaults.headers property:
javascriptaxios.defaults.headers.common['Authorization'] = 'Bearer YOUR_TOKEN'; axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
This code sets the Authorization header for all requests and the Content-Type header for POST requests. This means that these headers are automatically included in every request made through Axios, unless you override them in specific requests.
Example: Sending a POST Request with Request Headers
Suppose you need to send a POST request and include specific headers, such as Content-Type as application/json, and include an authentication token. Here is how to do it:
javascriptaxios.post('/login', { username: 'user', password: 'pass' }, { headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer YOUR_AUTH_TOKEN' } }) .then(response => { console.log('Authenticated', response); }) .catch(error => { console.log('Error', error); });
In this example, we send a POST request to the /login endpoint with the username and password in the request body. Additionally, we set the headers, including Content-Type and Authorization.
These methods allow you to set Axios request headers according to your needs, whether for individual requests or global configuration. When using Axios to interact with backend services, correctly setting request headers is crucial because they can contain important information for the server, such as authentication credentials, indicating the format of requests or responses.