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

查看:24
本文介绍了在 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 base location )

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天全站免登陆