What is the best way to structure api config file in react project?

眉间皱痕 提交于 2019-12-11 06:39:01

问题


I am developing react app and for api call i am using axios library. For all api calls i have app.js file, and then when some component needs to make api call just call function from that file. In short that would be little structre for now. In app.js file i have multiple api calls in which i am also seanding header config cause of token authorization. So i want to have a separate config file which will have default api header and all urls i am using for api call. I am looking for a best way to structure code.


回答1:


You can use a Component, which hold's your baseURL ( API base location )

Base URL Component:

import axios from 'axios';

const instance = axios.create({
    baseURL: 'https://react-test-b1ae5.firebaseio.com/'
});

export default instance;

Another file to hold you API calls part: You can give this component a desired name (Ex: axiousURL)

export const ADD_URL = 'AddArticle';
export const DELETE_URL = 'DeleteArticle';
export const UPDATE_URL = 'UpdateArticle';

Consuming:

import axios from '../../axios-orders';
import * as axiosURLS from '../../axiosURL'; 

axios.get( axios.baseURL+axiosURLS.DELETE_URL )
            .then( response => {
                // Some code//
            } )
            .catch( error => {
                // handle error
            } );



回答2:


If you are using redux, I would take a look in this lib redux-api-middleware.

I like to use it because it makes the code clear. Instead of use axios, it uses fetch to manage the requests.



来源:https://stackoverflow.com/questions/54179809/what-is-the-best-way-to-structure-api-config-file-in-react-project

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!