API 获取应该是前端还是后端? [英] Should API fetching be frontend or backend?

查看:32
本文介绍了API 获取应该是前端还是后端?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的网站应用程序在前端使用 React,我正在决定使用 ExpressJS 还是 Flask.py 作为后端.无论哪种方式,我都知道 React 有 API 获取功能,但也有其他后端专用框架.我的问题是,按照惯例,API 获取逻辑是前端还是后端的一部分?

My website application is using React for the frontend, and I'm deciding between ExpressJS or Flask.py for the backend. Either way, I know React has API fetching functions but also the other backend-dedicated frameworks. My question is, conventionally, would API fetching logic be part of the frontend or backend?

推荐答案

有些情况需要或更喜欢 API 获取在后端:

There are some conditions which require or prefer API fetching to be in the back-end:

  1. 当您需要使用安全凭据来访问 API 并且这些凭据需要保密时.

  1. When you need to use security credentials to access the API and you those credentials need to stay private.

当 API 不允许跨源访问时,您的前端无法直接访问它.

When the API does not permit cross origin access so your front-end could not directly access it.

当您需要对 API 结果进行一些处理并且希望将处理算法保密时(请记住,在前端完成的所有处理都可用供任何编码人员查看).前端代码没有秘密.

When you need to do some processing on the API results and you wish to keep the processing algorithms a trade secret (keep in mind that all processing done in the front-end is available for any coder to see). There are no secrets in the front-end code.

当前端设备可能没有适当的资源(CPU、内存等)来处理 API 结果时.对于较小的专用设备,情况尤其如此.

When the front-end device may not have appropriate resources (CPU, memory, etc..) to process the API results. This can particularly be the case with smaller dedicated devices.

当您不希望前端设备必须消耗电池能量来定期访问 API 时.如果您定期轮询某些 API 以寻找更改,则可能尤其如此.在这种情况下,您可能希望后端进行轮询,并让前端知道什么时候有实际操作.

When you don't want the front-end device to have to expend the battery energy to regularly access the API. This might particularly be the case if you're regularly polling some API looking for changes. In that case, you might want the back-end to do the polling and just let the front-end know when there is something to actually do.

当有理由对您对 API 的访问进行一些集中性能管理时,例如结果缓存或请求限制.

When there are reasons to do some centralized performance management of your access to the API such as caching of results or request throttling.

当所有前端设备可能没有适当的网络访问 API 服务器时.

When all front-end devices may not have proper network access to the API server.

如果将 API 访问权限放在后端没有令人信服的好处,那么让前端尽可能多地完成工作可能会更具可扩展性(对于您的服务器).

If there are no compelling benefits to putting the API access in the back-end, then it may be more scalable (for your server) to let the front-end do as much work as it can.

这篇关于API 获取应该是前端还是后端?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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