Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create configuration for axios for default request headers in every http call?

Tags:

reactjs

axios

https://github.com/MrFiniOrg/AxiosQuestion

I would like to have my project setup so that I do not have to specify the same request header in every http call.

I have searched this online but I have not been able to accomplish this in my project.

Would someone please assist me in resolving this issue I am having. I am new to react and axios and I am not sure how to configure this.

My project seems to be doing this but it is sending the request 2 times. One with the header and one without.

My axios call can be found in the app.js class component

like image 322
UncleFifi Avatar asked Aug 10 '18 22:08

UncleFifi


People also ask

How do I set the default header in axios?

Instead of adding the headers to each request, you can put them as default headers, and they will apply to all the requests. To do so, use the defaults. headers property of the axios object. This snippet will add the x-rapidapi-key header to all the requests.

Where do I put axios defaults baseURL?

To change the default base URL for Axios, we can set the baseUrl option when we're calling our axios instance. this. $axios({ url: "items", baseURL: "http://new-url.com" });

What is axios request config?

These are the available config options for making requests. Only the url is required. Requests will default to GET if method is not specified.


1 Answers

You can specify config defaults that will be applied to every request.

Global axios defaults

axios.defaults.baseURL = 'https://api.example.com'; axios.defaults.headers.common['Authorization'] = AUTH_TOKEN; axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'; 

For more specific info, please visit their docs.

UPDATE:

You can do it in two ways:

1. In your index.js file [meaning the top-level aka 'root' file] you can configure your request/ response methods. Something like this:

import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './App'; import registerServiceWorker from './registerServiceWorker'; import axios from 'axios';  axios.defaults.baseURL = 'https://jsonplaceholder.typicode.com'; axios.defaults.headers.common['Authorization'] = 'AUTH TOKEN'; axios.defaults.headers.post['Content-Type'] = 'application/json';  axios.interceptors.request.use(request => {     console.log(request);     // Edit request config     return request; }, error => {     console.log(error);     return Promise.reject(error); });  axios.interceptors.response.use(response => {     console.log(response);     // Edit response config     return response; }, error => {     console.log(error);     return Promise.reject(error); });  ReactDOM.render( <App />, document.getElementById( 'root' ) ); registerServiceWorker(); 

2. Or you can create a new file, a new instance of your axios.js file to be precise, and import the configurations separately in your components where you might need them. You could name it, eg axiosConfig.js, and put your specific configs inside of it. Something like this:

axiosConfig.js

// First we need to import axios.js import axios from 'axios'; // Next we make an 'instance' of it const instance = axios.create({ // .. where we make our configurations     baseURL: 'https://api.example.com' });  // Where you would set stuff like your 'Authorization' header, etc ... instance.defaults.headers.common['Authorization'] = 'AUTH TOKEN FROM INSTANCE';  // Also add/ configure interceptors && all the other cool stuff  instance.interceptors.request...  export default instance; 

After that you would import this file to components that need it and use it instead of the previous Axios [node_modules] import, like this:

Example.js

import React, { Component } from 'react'; // import axios from 'axios'; We don't need this anymore import axiosConfig from '../../axiosConfig'; // But instead our new configured version :)  class Example extends Component {     state = {         data: [],         error: false     }      componentDidMount () {         // We could name (import) it as axios instead, but this makes more sense here ...          axiosConfig.get('/posts' )             .then(response => {                    this.setState({data: response});                 });             })             .catch(error => {                 this.setState({error: true});             });     } 

NOTE: You can combine these two methods as needed, but remember that the configurations made in your configAxios.js file will overwrite those made in your index.js file [if they are the same configurations, that is :) ]

like image 158
Dzenis H. Avatar answered Sep 28 '22 03:09

Dzenis H.