Express router working fine locally but not on heroku

My express app works fine on the localhost but it does not work on Heroku.
When I added a line it stops working and

the line is

app.use("/api/product", require("./routes/product"))

Here is the code
Index.js

const express = require("express");
const app = express();

const port = process.env.PORT || 5000;


app.get("/", (req, res) => {
    res.send("responded")
});

app.use(express.json())

app.use("/api/product", require("./routes/product"))


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

product.js

const express = require("express");
const router = express.Router();

router.get("/", async (req, res) => {
    try {
        res.json({
            status: 200,
            message: "Data has been successfully fetched"
        });
    }
    catch (error) {
        console.log(error);
        return res.status(400).send("server error")
    }
})

module.exports = router;

package.json

{
  "name": "backend-test",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "node index.js",
    "test": "echo "Error: no test specified" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.17.3"
  }
}

Folder structure

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You would wanna switch your route handlers place. Otherwise you will never rich your api, as the first catches all requests.

const express = require("express");
const app = express();

const port = process.env.PORT || 5000;
app.use(express.json())

app.use("/api/product", require("./routes/product"))
app.get("/", (req, res) => {
    res.send("responded")
});

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


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x