reactjs - LAMP Droplet 上的 MERN 堆栈 (DigitalOcean)
问题描述
我有一个 MERN 应用程序分为:
1.client
文件夹:前端代码(REACT 应用程序)
2.server
文件夹:API 代码(Express,NodeJs)
由于某种原因,前端调用了/api
应用程序的一部分,但没有返回响应。是 Apache2 设置中的问题吗?或反应应用程序中的东西。ExpressJs(后端)和 ReactJs(前端)之间的链接通常是如何完成的。
路由是通过 Apache2 反向代理设置的
<IfModule mod_ssl.c>
<VirtualHost *:443>
ServerName example.com
ServerAlias www.example.com
DocumentRoot /var/www/example.com/
Options -Indexes
ProxyRequests on
ProxyPass /api https://example.com:3000/
ProxyPassReverse /api https://example:3000/
ProxyPass / https://example.com:7000/
ProxyPassReverse / https://example:7000/
Include /etc/letsencrypt/options-ssl-apache.conf
SSLCertificateFile /etc/letsencrypt/live/example.com/fullchain.pem
SSLCertificateKeyFile /etc/letsencrypt/live/example.com/privkey.pem
</VirtualHost>
</IfModule>
解决方案
我认为问题在于您忘记了为生产准备 React 应用程序。你一直在开发它并使用 react-scripts-start 或类似的东西。完成开发后,您必须运行 react-scripts-build 以便您的代码可以转换为浏览器可以读取的内容。Web 浏览器不读取诸如 import 和 require 之类的内容。
这是有关准备生产的信息(非常简单) https://create-react-app.dev/docs/production-build
以下是有关如何将其与后端集成的信息: https ://create-react-app.dev/docs/deployment#other-solutions
本质上:在您的客户端文件夹中运行
npm build
在你的 server.js 添加
app.use(express.static(__dirname + '/build')
现在客户端从您的后端服务器请求您的 index.html 并为您的 react 应用程序提供服务。额外的好处:不再有 CORS 错误。您为 CORS 所做的任何解决方法都应该将其删除。
推荐阅读
- reactjs - 在 firebase 数据库上,Redux 复制存储中的最后一个数据
- json - Pojo 到带有验证的 json
- hibernate - JPA,如何使用相同的条件查询对象来获取结果列表并进行选择计数
- java - 重现 java.io.IOException: 数据错误 (CRC)
- c# - 用定义长度的空格分割字符串
- spring-boot - 使用 FlywayMigrationStrategy 的多个 Flyway
- c - 关于直接访问函数返回的结构成员的警告
- arrays - Symfony Doctrine Collection 获得单一值
- c# - 解决此错误:“名称空间'System'中不存在类型或名称'Collections'。(您是否缺少程序集或引用)”?
- python - 根据某个关键字恢复python脚本