Upload backend and frontend together in heroku

0

I want to upload an application with backend in nodejs and frontend in react without creating 2 projects in heroku.

The directories of my application are like this:

  • My Application

    • app - "This folder contains the frontend created with create-react-app"
    • routes
    • server.js

I want the frontend to be displayed when the heroku application is opened, but also the data from the backend is being used.

Is it possible to do this?

    
asked by Edwin V 05.12.2018 в 03:50
source

1 answer

2

Of course you can integrate the "frontend" and the "backend" within the same project, given the end the "frontend" will end up serving through a server http (backend).

To explain this I will build on the Express framework in the backend, since you do not mention it.

You just have to configure the server to take the "app" folder as a directory of static files, for which we will use the express function "static". I would only recommend that you define the routes of your server starting with '/ api /' so as not to confuse them with any route of static files, for example: ' link '.

Taking into account the above, your "server.js" file should look like the following code:

/**
 * REST API
 */

// Dependecies
const express = require('express');
const path = require('path');

// Initialize http server
const app = express();

// Middlewares
app.use('/', express.static(path.join(__dirname, '/app/')));

// Routes

// test route
app.get('/api/test', (req, res, next) => {
  try {
    res.status(200).send('hello world');
  } catch (err) {
    next(err);
  }
});

// start the server
app.listen(process.env.PORT || 3000, () => {
  console.log('server on port', process.env.PORT || 3000);
});
    
answered by 06.12.2018 в 13:34