How do you merge a front and back end together?

I am building a multi-step checkout process. I have mostly finished the back end, and I used pug templates to test the process. Then I worked on a more slick React front end. They are in 2 different repos.

Once React is ready to send out a request with the right data, I want to merge the projects together (removing pug as the view engine and using only the Express endpoints). I am a bit lost on this part though. How is it normally done?

Not exactly sure what your setup is but I think I had the same kind of question on a project I’m working on.

You have your endpoints on the express server and express can also serve your static files too at the root endpoint or wherever but you don’t have to do it that way.

You can have a separate project that just sends requests to your express app endpoints fetch(http://localhost/getTheData/).

You could also drag the bundled React files into your express static files folder and serve them from express, or host the static files separately, or make your express project folder have all the react dependencies in the package.json and develop only in that one project folder.

I’m doing one project folder for my express API and another project folder for my React frontend, for now at least.

2 Likes

Agreeing with @br3ntor, and thought I’d share an example of how I structured my last Express / React app. It’s not the only method, but one working solution.

I added a Client folder that contained the front end. The project looked something like this:

> Client
     > Public
          index.html
     > Src
          > Components
          app.js     
     package.json
package.json
server.js

The front end fetches data from the back end, as @br3ntor described, when the component mounts:

    componentDidMount() {
        this.callApi()
            .then(res => {
                this.setState({ data : res.data })
            })
            .catch(err => console.log(err));
    }

    callApi = async () => {
        const response = await fetch('/api/YOUR-END-POINT');
        const body = await response.json();
        if (response.status !== 200) throw Error(body.message);
        return body;
    };

On the server side, you’d handle that request with something like this:

app.get('/api/YOUR-END-POINT', (req, res) => {
     // Assign your data (from mongoDB, etc.) to YOUR_DATA
     res.status(200).send(YOUR_DATA)
});
2 Likes