部署独立的React Frontend和Django DRF API [英] Deploying Seprate React Frontend and Django DRF API

查看:48
本文介绍了部署独立的React Frontend和Django DRF API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用create-react-app制作的react前端,用于部署我只做npm run build的生产版本.我的应用程序使用Django Rest FrameWork API后端.

I have a react frontend made with create-react-app to deploy a production build of this I just do npm run build. My app uses a Django Rest FrameWork API backend.

如何设置要在单个服务器上部署的应用程序.有没有一种方法可以在Django中存储React Frontend并路由到它,并让来自Frontend的请求命中api/视图或端点.

How can I setup the app for deployment on a single server. Is there a way I can store the React Frontend and route to it in Django and have requests from the Frontend hit a api/ view or endpoint.

部署这样的最佳策略是什么?或者最好在不同的服务器上拼装托管前端和后端更好?

What are the best strategies for deploying something like this or is it better to host the Frontend and Backend desperately on different servers?

基本上:如何将我的React前端构建结合到Django DRF中进行部署?

Basically: How do I combine my react frontend build into Django DRF for deployment?

推荐答案

您可以将django用作您的react应用程序的容器. 在react项目的根文件夹中运行"npm run build".它将生成构建目录并捆绑所有javascript文件. 将此构建文件夹放在django项目的根目录中.并在settings.py文件中进行以下更改:

You can use django as a container for your react app. Run "npm run build" inside your react project root folder. It will generate build directory and bundle all the javascript files. Put this build folder inside the root directory of your django project. and make the following changes in settings.py file:

STATICFILES_DIRS = (
    ...
     os.path.join(BASE_DIR, 'build/static'),
     os.path.join(BASE_DIR, 'build')
...
)

并在urls.py中输入如下内容:-

and in urls.py make an entry like :-

url(r'^$', mView.login, TemplateView.as_view(template_name = 'index.html'))

使用"axios"或本机提取api从react应用进行api调用.

Make api calls from react app using 'axios' or native fetch api.

此后,每当您为django项目点击URL时,它将被重定向到react应用程序.您可以使用apache wsgi托管它.对我来说很好.

After this whenever you hit the url for your django project it'll be redirected to the react app. You can host this with apache wsgi. Works fine for me.

以下链接可能有帮助: https://medium.com/alpha-coder/heres-a-dead-simple-react-django-setup-for-your-next-project-c0b0036663c6

Following link might help: https://medium.com/alpha-coder/heres-a-dead-simple-react-django-setup-for-your-next-project-c0b0036663c6

这篇关于部署独立的React Frontend和Django DRF API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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