How to use multiple baseURL axios in ReactJS?

Asked
Active3 hr before
Viewed126 times

8 Answers

reactjsmultiple
90%

As said you could create two instances of axios and use them as needed:, Why do companies interview candidates they don't seem to seriously consider for the role? ,Please be sure to answer the question. Provide details and share your research!

In you BASE URL file:

import axios from 'axios';

const setAuthToken = (token) => {
   if (token) {
      axios.defaults.headers.common.Authorization = `Bearer ${token}`;
   } else {
      delete axios.defaults.headers.common.Authorization;
   }
};

const mainAxios = axios.create({
   baseURL: 'http://localhost:3000/summary'
});

const profileAxios = axios.create({
   baseURL: 'http://localhost:6000/profile'
});

export default setAuthToken;
export {
   mainAxios,
   profileAxios
};

Then in your API ACTION file:

import {
   profileAxios
} from 'path/to/baseurl';

export const login = ({
   email,
   password
}) => async (dispatch) => {

   const userData = {
      username: email,
      password,
   };

   try {
      const res = await profileAxios.post('/license-api/auth/login', userData, config);
      dispatch({
         type: LOGIN_SUCCESS,
         payload: res.data.token,
      });
   } catch (error) {
      dispatch({
         type: LOGIN_FAIL,
      });

   }
};
load more v
88%

In some cases my app requires different defaults from the standard ones, and I've been dealing with this by putting something like this in the app's entry point:,@mzabriskie That makes sense. There are some differences between the structure of defaults and config though. For example:,@chibicode to bad, i use axios because the request and response interceptors, it would be cool to be able to use nock with this library

let axiosDefaults = require('axios/lib/defaults');
axiosDefaults.baseURL = 'http://somesite.com';
load more v
72%

@Geoff Graham (can’t seem to reply directly) I never really understood that:,with our hand-crafted weekly newsletter,The related posts above were algorithmically generated and displayed here without any load on our servers at all, thanks to Jetpack.

It can be installed using npm (or yarn):

npm install axios
load more v
65%

Then we'll touch on more advanced features like creating an Axios instance for reusability, using async-await with Axios for simplicity, and how to use Axios as a custom hook.,The .create() function returns a newly created instance, which in this case is called client.,The quickest way to create a new React application is by going to react.new.

Pretag
 Pretag team - issue, fix, solve, resolve
75%

Now when you need to make a network request, import the axios instance instead of the node_module axios. , We strive for transparency and don't collect excess data. , Email sourabh.ocean@gmail.com

import axios from 'axios';
import {
   BASE_PATH
} from "./main.local";

const getBlogs = () => {
   return axios.get(BASE_PATH + "getBlogs");
}
load more v
40%

Axios is basically an external library, which is used to make promise based HTTP calls(fetch made easy, plus gives us structured responses). Its one of those recommenced libraries, used with ReactJs. What people don’t really realise, it does more than making a get/post request.,I personally use the response interceptor more than the request interceptor.,Setting token for the instances that required authorisation.

Axios is basically an external library, which is used to make promise based HTTP calls(fetch made easy, plus gives us structured responses). Its one of those recommenced libraries, used with ReactJs. What people don’t really realise, it does more than making a get/post request.

npm i--s axios

Let’s look at a basic implementation:

import axios from 'axios';
axios.get('https://jsonplaceholder.typicode.com/todos').then(func)

Let create our instance by using the create method which is part of the axios import you did above.

const instance = axios.create()

Let’s set our endpoint as the baseurl for the above instance.

const instance = axios.create({
   baseURL: "https://jsonplaceholder.typicode.com/"
})
load more v
22%

Instances: Create reusable instances with baseUrl, headers, and other configuration already set up.,It is suggested to add following configurations in componentDidMount of App.jsx so that the axios instance is prepared to be used throughout the app.,Interceptors: Access the request or response configuration (headers, data, etc) as they're outgoing or incoming. These functions can act as gateways to see configuration or add/modify data.

1 $ yarn add axios
load more v
60%

In this component, we have exported the axios package and created an instance with all default parameters. For this articles, we are concerned with baseURL only. Now we need to import this file throughout our application where we need to make an API call.,In this example we are using our custom axios component and not the one shipped by Axios package. This component is set with default baseURL of example.com and so we do not need to provide full url in axios.get.,You can also set default headers, request / response parameters while setting up Axios instance.

Create a component, axios.js

import axios from 'axios';
const instance = axios.create({
   baseURL: 'https://www.example.com'
});
export default instance
load more v

Other "reactjs-multiple" queries related to "How to use multiple baseURL axios in ReactJS?"