简体   繁体   English

React.JS react-create-app 后端相同端口

[英]React.JS react-create-app backend same port

I am new to React.JS and using react-create-app to setup the project.我是 React.JS 的新手,并使用 react-create-app 来设置项目。

I am wondering is there a way to use the same host and port to response for API requests, (the server serves both front-end and back-end, like in Django).我想知道有没有办法使用相同的主机和端口来响应 API 请求(服务器同时服务前端和后端,就像在 Django 中一样)。

The doc mentions about this but does not go into details.该文档提到了这一点,但没有详细说明。

By same host and port I mean I only need one terminal and run npm start once.通过相同的主机和端口,我的意思是我只需要一个终端并运行 npm start 一次。

If there is only for development you can simply add如果仅用于开发,您可以简单地添加

"proxy": "http://localhost:8000/"

to your package.json .到您的package.json

This will proxy your API queries from React to your other app working on another port (there 8000).这会将您的 API 查询从 React 代理到在另一个端口(有 8000)上工作的其他应用程序。

After you finish, you need to build production code ( npm build command), which result is an index.html which loads builded js and css bundles.完成后,您需要构建生产代码( npm build命令),其结果是一个index.html ,它加载npm build js 和 css 包。

From Django you need only point your IndexView to this file (you can do this as TemplateView, but maybe simpler is only render like there:在 Django 中,您只需要将 IndexView 指向此文件(您可以将其作为 TemplateView 执行此操作,但也许更简单的只是像这样渲染:

class IndexView(View):
    def get(self, request):
        index = open(str(settings.BASE_DIR.path('build/index.html')), 'r')
        return HttpResponse(content=index.read())

Then only use your API from React - from this point both will work on common port.然后只使用来自 React 的 API - 从这一点来看,两者都可以在公共端口上工作。

Back to development mode - you can also configure your Webpack to build your app everytime you save changes and only run them from Django (or Rails, or Node, or whatever is your backend), but I prefer to use proxy, which keep both apps in their native contexts until you finish development.回到开发模式 - 您还可以配置 Webpack 以在每次保存更改时构建您的应用程序,并且仅从 Django(或 Rails、Node 或任何后端)运行它们,但我更喜欢使用代理,它同时保留两个应用程序在他们的原生环境中,直到您完成开发。 One disadventage of this solutions is that you need always run both apps simultaneously.此解决方案的一个缺点是您需要始终同时运行两个应用程序。

Some usefull info and soultions about this I found there: https://www.fullstackreact.com/articles/using-create-react-app-with-a-server/我在那里找到了一些有用的信息和解决方案: https : //www.fullstackreact.com/articles/using-create-react-app-with-a-server/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM