Bundle React/Express App for production

前端 未结 1 830
名媛妹妹
名媛妹妹 2021-01-15 09:23

My app is built with \"create-react-app\" and also Express.js as back-end. How should I set up for the app for production?

Here is my user.js file from Express:

相关标签:
1条回答
  • 2021-01-15 09:58

    If Express acts as both your API and your application server, at a basic level you'd need to setup Express to load the index.html of the React application when no other API routes are caught. You would do this by using sendFile() along with Node's path, registering a "catch-all" route after all your other API endpoints, in the main file for your Express application.

    app.use('/users', usersRouter);
    
    app.use('*', function (request, response) {
      response.sendFile(path.resolve(__dirname, 'index.html'));
    });
    

    The path within sendFile() needs to point to the location of the index.html of the React client/frontend applicaiton. Exactly what goes into sendFile() entirely depends on the structure of your project. If for exampple you have the React application in a folder called client which has a build folder generated by create-react-app npm run build, the sendFile() would look like:

    app.use(express.static(path.join(__dirname, 'client', 'build')));
    
    // API route
    app.use('/users', usersRouter);
    
    app.use('*', function (request, response) {
      response.sendFile(path.join(__dirname, 'client', 'build', 'index.html'));
    });
    

    The * in app.use() such as app.use('*', function (request, response)); means effectively all HTTP verbs (GET, POST, PUT, etc). If you do NOT put this after your API routes/paths, it will prevent your React client application from making calls to the API as it will catch all requests, order is very important.

    Then you simply build the React application then run the Express application.

    Hopefully that helps!

    0 讨论(0)
提交回复
热议问题