Home > Software engineering >  deploying react app in Heroku gets a blank page
deploying react app in Heroku gets a blank page

Time:05-31

my problem is when I try to use Heroku open after I was deployed my react app I get a blank page with the same title in my index.html, what I am trying to do is deploy my app to Heroku the backend and the frontend, when I run it locally it's works

server.js

import express from 'express';
import mongoose from 'mongoose';
import Messages from "./dbMessages.js";
import Pusher from "pusher";
import path from 'path';
import cors from 'cors';
// importing
const __dirname = path.resolve(path.dirname(''));

//app config
const app =express();
const port=process.env.PORT || 9000;

if(process.env.NODE_ENV === 'production')
{
    app.use(express.static('./whatsapp-frontend/buid'))
    app.get('*',(req, res) => {
        res.sendFile(path.join(__dirname,'./whatsapp-frontend','build','index.html'))
    })
}
const pusher = new Pusher({
    appId: "1322521",
    key: "11eff1cbbe0451f43821",
    secret: "9bcbb587eab320e5786b",
    cluster: "ap2",
    useTLS: true
  });
//middleware
app.use(express.json());
  app.use(cors())



//DB config
const connection_url='mongodb srv://admin:[email protected]/whatsappdb?retryWrites=true&w=majority';
mongoose.connect(connection_url);


const db =mongoose.connection

db.once('open',()=>{
    console.log('Db connect');

    const msgCollection =db.collection('messagecontents')
    const changeStream= msgCollection.watch();

    changeStream.on("change",(change)=>{
        console.log("a change occured",change);


        if(change.operationType === 'insert'){
            const messageDetails=change.fullDocument;
            pusher.trigger('messages','inserted',
            {
                name:messageDetails.name,
                message:messageDetails.message,
                timpestamp:messageDetails.timpestamp,
                received: messageDetails.received
            }
            
            );
        } else{
            console.log('Eror trigerring pusher')
        }
    

    
    });
});




//api routes
app.get('/',(req,res)=>res.status(200).send('hello world'));


app.get('/messages/sync',(req,res)=>{
    Messages.find((err,data) => {
        if(err){
            res.status(500).send(err)
        }else{
            res.status(200).send(data)
        }
    })
})

app.post('/messages/new',(req,res)=>{


    const dbMessage =req.body;
    Messages.create(dbMessage,(err,data)=>{
        if(err)
        {
            res.status(500).send(err)
        }else{
            res.status(201).send(`new message created:\n ${data}`)
        }
    });
});

//listen
app.listen(port,()=> console.log(`Listening to localhost:${port}`));

this is my package.json of server.js

{
    "name": "whatsapp-backend",
    "version": "1.0.0",
    "description": "",
    "main": "server.js",
    "type": "module",
    "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1",
        "start": "node server.js",
        "whatsapp-frontend": "npm start --prefix whatsapp-frontend",
        "dev": "concurrently\"npm run server\" \npm run whatsapp-frontend\"",
        "heroku-postbuild":"NPM_CONFIG_PRODUCTION=false npm install --prefix whatsapp-frontend && npm run build  --prefix whatsapp-frontend"       
    },
    "author": "Nadav Mazuz",
    "license": "ISC",
    "dependencies": {
        "cors": "^2.8.5",
        "express": "^4.17.2",
        "mongoose": "^6.1.3",
        "pusher": "^5.0.0"
    }
}

this is my index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    <meta
      name="description"
      content="Web site created using create-react-app"
    />
    <link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
    <!--
      manifest.json provides metadata used when your web app is installed on a
      user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
    -->
    <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
    <!--
      Notice the use of %PUBLIC_URL% in the tags above.
      It will be replaced with the URL of the `public` folder during the build.
      Only files inside the `public` folder can be referenced from the HTML.

      Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
      work correctly both with client-side routing and a non-root public URL.
      Learn how to configure a non-root public URL by running `npm run build`.
    -->
    <title>React</title>
  </head>
  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
    <!--
      This HTML file is a template.
      If you open it directly in the browser, you will see an empty page.

      You can add webfonts, meta tags, or analytics to this file.
      The build step will place the bundled scripts into the <body> tag.

      To begin the development, run `npm start` or `yarn start`.
      To create a production bundle, use `npm run build` or `yarn build`.
    -->
  </body>
</html>

and here is my result: https://immense-waters-47367.herokuapp.com/

thanks for the assistance!

CodePudding user response:

I think you made a typo here should be /build

app.use(express.static('./whatsapp-frontend/buid'))

Also, if that doesn't work then look into your heroku-postbuild in the root of app and see if thats installing everything

  • Related