在React项目中构造api配置文件的最佳方法是什么? [英] What is the best way to structure api config file in react project?

查看:129
本文介绍了在React项目中构造api配置文件的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发react应用,对于api调用,我正在使用axios库.对于所有api调用,我都有app.js文件,然后当某些组件需要进行api调用时,只需从该文件调用函数即可.简而言之,目前尚无定论.在app.js文件中,我有多个api调用,在这些调用中,我还想查找令牌授权的标头配置原因.所以我想有一个单独的配置文件,它将具有默认的api标头和我用于api调用的所有URL.我正在寻找一种构造代码的最佳方法.

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.

推荐答案

您可以使用一个组件,该组件保存您的 baseURL ( API基本位置)

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

基本URL组件:

import axios from 'axios';

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

export default instance;

另一个用于保存API调用的文件:您可以为该组件指定所需的名称(例如: axiousURL )

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

消费:

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

这篇关于在React项目中构造api配置文件的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆