0
const express = require("express");
const app = express();
const bodyParser = require("body-parser");
const port = process.env.PORT || 3002;

const cors = require("cors");
const path=require("path");
const routing  = require("./routing/route");
require('dotenv').config();
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

app.use("/",routing);

app.use(function (err, req, res, next) {
  console.log("hii")
  res.status(500).send({ message: err.message });
});

if(process.env.NODE_ENV ==="production"){

  app.use(express.static("client/build"));

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

app.listen(port, () => {
  console.log(` Server is started at http://localhost:${port}`);
});

What I have noticed that my backend is running as in log I can see the //console.log( Server is started at http://localhost:${port})// this part from my code.

But my frontend is that working.

In the log file I can see these error.

TypeError: path must be absolute or specify root to res.sendFile Error: ENOENT: no such file or directory, stat '/app/index.html'

I guess both the error are related to the same path.enter image description here

I have attached my folder structure also

Piyush Raj
  • 13
  • 3
  • I have tried path.join as I have seen it other places but I am getting a internal server error in that case. – Piyush Raj Aug 20 '20 at 12:27

1 Answers1

0

It's very similar to this question (which already has answer) - I sure you can find answer there.

Express-js can't GET my static files, why?

  • How can I apply the following solution to my problem?? Am I doing anything wrong in app.use(express.static("client/build")); – Piyush Raj Aug 20 '20 at 12:56
  • Actually there is some problem in the Heroku git repository my client folder empty, so the static function would not able to identify the path and hence it's showing not found. – Piyush Raj Aug 22 '20 at 12:35