首页 > 解决方案 > 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>

只是为了澄清我想要实现的目标: 在此处输入图像描述

标签: reactjsexpressreverse-proxydigital-oceanmern

解决方案


我认为问题在于您忘记了为生产准备 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 所做的任何解决方法都应该将其删除。


推荐阅读