axios在反应中忽略了baseURL

时间:2020-05-11 03:46:40

标签: javascript reactjs axios

在我的app.js中

useEffect(() => {
    axios.defaults.headers.common["token"] =
      process.env.REACT_APP_SITE_TOKEN;
    axios.defaults.baseURL = "https://api.example.com";
  }, []);

在我的redux操作文件中:

export const getCollectionByToken = (token) => async (dispatch) => {
  console.log(axios.defaults); //logs https://api.exapmle.com
  try {
    const res = await axios.get("/collections/" + token);
    console.log(res);
    dispatch({ type: SET_CURRENT_COLLECTION, payload: res.data });
...

但是不知何故,请求将转到http://localhost:3000/collection/<token>

2 个答案:

答案 0 :(得分:2)

UseEffect在安装组件之后运行,并且您的redux动作可能在此之前进行编译。浏览器console.log有时会出现错误,并以错误的顺序打印。

尝试:

export const getCollectionByToken = (token) => async (dispatch) => {
  axios.defaults.headers.common["token"] =
      process.env.REACT_APP_SITE_TOKEN;
    axios.defaults.baseURL = "https://api.example.com";
  try {
    const res = await axios.get("/collections/" + token);
    console.log(res);
    dispatch({ type: SET_CURRENT_COLLECTION, payload: res.data });
    ...

或根据document,在某处创建实例,例如文件axiosConfig.ts

import axios from 'axios'

// Set config defaults when creating the instance
const axiosInstance = axios.create({
  baseURL: 'https://api.example.com'
});

// Alter defaults after instance has been created
axiosInstance.defaults.headers.common['token'] = process.env.REACT_APP_SITE_TOKEN;

export default axiosInstance;

然后,当您要使用axios时,直接从库中导入实例而不是axios:

import axiosInstance from './axiosConfig';

export const getCollectionByToken = (token) => async (dispatch) => {
  try {
    const res = await axiosInstance.get("/collections/" + token);
    dispatch({ type: SET_CURRENT_COLLECTION, payload: res.data });
    ...

答案 1 :(得分:0)

您可以添加拦截器,也有用于axios的es6类包装器。

$ npm install @eneto/axios-es6-class

您需要创建自己的api类,该类将从Api扩展。

假设我们正在创建一个class UsersApi

import { Api } from '@eneto/axios-es6-class';

// process.env.API_BASE_URL = localhost:3001

export class UserApi extends Api {
    public constructor (config) {
        super(config);

        // this middleware is been called right before the http request is made.
        this.interceptors.request.use(param => {
            const {API_BASE_URL} = process.env;
          return {
              ...param,
              baseUrl: API_BASE_URL,
              defaults: {
                  headers: {...param.defaults.headers}
              }
          }
        });

        // this middleware is been called right before the response is get it by the method that triggers the request
        this.interceptors.response.use(param => {
          return {  ...param}
        });

        this.userLogin = this.userLogin.bind(this);
        this.userRegister = this.userRegister.bind(this);
    }

    public userLogin (credentials) {
        return this.post("/login", credentials)
            .then(this.success);
    }

    public userRegister (user) {
        return this.post("/register", user)
            .then(this.success)
            .catch((error) => {
                throw error;
            });
    }


}