MERN Stack on a LAMP Droplet (DigitalOcean)

MERN Stack on a LAMP Droplet (DigitalOcean)

我有一个 MERN 应用程序拆分为:

1. client 文件夹:前端代码(REACT 应用程序)
2. server 文件夹:API 代码(Express、NodeJs)

出于某种原因,前端调用了应用程序的 /api 部分,但没有 return 响应。是 Apache2 设置中的问题吗?或者反应应用程序中的东西。 link 通常是如何在 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>

只是为了澄清我想要实现的目标:

I think the issue is that you've forgotten to prepare your React App for production. You spent all the time developing it and using react-scripts-start or something similar. When you are done developing you have to 运行 react-scripts-build so that your code can be transpiled into something the browser can read. Web browsers don't read things like import and require.

Here's info on preparing for production (it's very simple) https://create-react-app.dev/docs/production-build

And here's info on how to integrate it with your back end: https://create-react-app.dev/docs/deployment#other-solutions

Essentially: In your client folder 运行

npm build

In your server.js add

app.use(express.static(__dirname + '/build')

Now a client requests your index.html from your back end server and it serves your react app. Added benefit: no more CORS errors. Any work-around you did for CORS you should probably take it out.