如何在ReactJS中使用多个baseURL axios?

时间:2020-03-26 08:10:22

标签: reactjs react-redux axios react-hooks

我有一个配置文件。我在设置整个应用程序的baseURL的同时,还为整个API请求保存了承载令牌。我在这里要添加另一个api。我不知道如何添加另一个baseURL并在我的API请求中使用它。在这里,我正在分享执行的代码。

基本URL文件:

import axios from 'axios';
axios.defaults.baseURL = http://localhost:3000/summary;

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

export default setAuthToken;

API操作文件:

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

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

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

  }
};

我需要在BASE URL FILE中添加这样的另一个URL

axios.defaults.baseURL = http://localhost:6000/profile

如何添加此代码并将其在API操作文件中使用。

请帮助我。

预先感谢

2 个答案:

答案 0 :(得分:1)

如前所述,您可以创建两个instances of axios并根据需要使用它们:

在您的 BASE URL 文件中:

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 };

然后在您的 API ACTION 文件中:

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,
    });

  }
};

答案 1 :(得分:0)

上面的代码运行良好。我没有看到 setAuthToken 在哪里被调用,所以如果你不想手动调用 setAuthToken 那么你可能想要这样做。

final List<XFile>? images = await _picker.pickMultiImage(source: ImageSource.gallery);