How to deploy MERN app, i got 'cannot get /'

Viewed 945

I'm trying to deploy a MERN app on Azure but when I check my url I got cannot the error cannot get /.

I have tried to start my node server on my local machine on production env and I just have a blank page.

I try to check if there is not a path problem in my code so in server.js I have console.log(path.resolve(__dirname, '../client/build')); on my local it show me the correct path but on azure it result of undefined so I guess on azure I can't use __dirname

My app tree is like this:

|--client
   |--build
|--node_modules
|--server
   |--server.js
|--package.json

My server.js

const dotenv = require('dotenv');
dotenv.config();
const express = require("express");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const app = express();
const passport = require("passport");
const path = require('path');
const users = require("./routes/api/users");
// Bodyparser middleware
app.use(
   bodyParser.urlencoded({
        extended: false
    })
);
app.use(bodyParser.json());

// DB Config
const db = require("./config/key.js").mongoURI;
console.log(db);
// Connect to MongoDB
mongoose.Promise = global.Promise;
mongoose.connect(db, { useNewUrlParser: true })
   .then(() => console.log("MongoDB successfully connected"))
   .catch(err => console.log(err));

// Passport middleware
app.use(passport.initialize());
// Passport config
require("./config/passport")(passport);
// Routes
app.use("/api/users", users);

// Serve static assets if in production
if (process.env.NODE_ENV === 'production') {
    // Set static fold
    console.log(path.resolve(__dirname, '../client/build'));
    app.use(__dirname, express.static('../client/build'));

    app.get('*', (req, res) => {
        res.sendFile(path.resolve(__dirname, '../client', 'build', 
'index.html'));
    });
}

const port = process.env.PORT || 5000;
app.listen(port, () => console.log('Server up and running on port 
${port} !'));

To be honest I don't know what I expect to have.

When I develop on my local I have my node-js server started and my react server started too.

When I try to make some search about how to deploy I can only find tutorial which explain 'copy paste this and it will work' but I have no idea how it work ?

With all my search, I guess I have to run the node server and it will render my front-end from the index.html from my build repository then why on azure I got cannot get / ?

##EDIT##

Actually the problem was Azure doesn't start my server.js in production mode so my condition was never hit.

I don't have this cannot get / any more and I have the same problem in local, I have got a blank page. If I open the inspector I can see it's my index.html and I can in the console I have this error Uncaught SyntaxError: Unexpected token < main.a3362a52.chunk.js:1 Uncaught SyntaxError: Unexpected token < index.bundle.js:1

Could it be the cause of the blank page ?

0 Answers
Related