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

前端 未结 3 1665
你的背包
你的背包 2020-12-13 15:51

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.

3条回答
  •  忘掉有多难
    2020-12-13 16:31

    I also had the same issue and solution was to locate them in index.js:

    import React from 'react';
    import ReactDOM from 'react-dom';
    import { BrowserRouter } from 'react-router-dom';
    import axios from 'axios';
    import './index.css';
    import 'bootstrap/dist/css/bootstrap.css';
    import App from './components/app/App';
    import * as serviceWorker from './serviceWorker';
    
    axios.defaults.baseURL = process.env.REACT_APP_BE_URL;
    
    ReactDOM.render(
      
        
      ,
      document.getElementById('root'),
    );
    
    serviceWorker.unregister();
    

    Also, I use .env files to keep for example base urls:

    .env.production

    REACT_APP_BE_URL=http://production-url-to-backend/
    

    .env.development

    REACT_APP_BE_URL=http://localhost:3000/
    

    And when you run locally .env.development will be used, for production build (npm run build) .env.production will be used.

    • More about axios global confg: https://github.com/axios/axios#global-axios-defaults
    • More about .env: https://facebook.github.io/create-react-app/docs/adding-custom-environment-variables

提交回复
热议问题