Axios is a JavaScript library that can run on the browser and on NodeJS, in simple term without much complication Axios is used to make Request (POST, GET, UPDATE, DELETE) from the frontend of an application built with JavaScript to the backend built with any language. It is very popular and widely used by frontend and Fullstack developer. There are different ways we can use Axios in our React app and sometimes we need to perform some extra configuration on Axios when making request to a server such configuration will help in avoiding some error like CORS, unauthorized request (when access token is needed) and so more. There are two place recommended in configuring axios We can either create a separate JS file and put all Axios configuration in it and then export it to desired component that make http request. Or we can make all configuration in the app.js file, this will make the configuration available in all components. Example below
import axios from "axios";
axios.defaults.baseURL = "http://127.0.0.1:8000/";
axios.defaults.withCredentials = true;
axios.interceptors.request.use(function (config) {
const token = localStorage.getItem("token");
config.headers.Authorization = token ? `Bearer ${token}` : "";
return config;
});
axios.defaults.headers.post["Content-Type"] = "application/json";
axios.defaults.headers.post["Accept"] = "application/json";
function App() {
return (
<div>
<h2>Axios simple confi</h2>
</div>
);
}
export default App;
With the code above axios configuration will be available in all our components, this is a good practice and a recommended place for placing axios configuration aside creating another configuration separate file