How do I deploy ReactJs + Node app onto remote ser

2019-08-25 07:29发布

问题:

Assuming I'm not using any third party service, just a dedicated server, how do I go about doing this? I'd like to use this as an example. In it, there's a build folder. I understand I can pretty much just copy paste the contents of this into the public_html of the remote server after doing npm run build but then there's the /server folder which is using node and possibly interacting with the database, can't be put in with the rest of the build js.

My best guess is that I would npm run build and ftp the contents of the build folder to public_html on the remote server then I would put the contents of the server folder onto another subdomain and then ssh into the server and do npm start in said subdomain? Or possibly have it in a subfolder of the public_html. I'm from a php background and used to vanilla js + php so any advice is much appreciated.

回答1:

First create build folder in react side by running

npm run build

then add these lines of code in the node side in app.js/index.js

app.use(express.static("<your_react_app_folder>/build"));
if (process.env.NODE_ENV === "production") {
  const path = require("path");
  app.get("/*", (req, res) => {
    res.sendfile(path, resolve(__dirname, "../<your_react_app_folder>", "build", "index.html"));
  });
}

Then deploy it to heroku/remote server.

Note: remember to remove /build line from .gitignore file