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
CodePudding user response:
You would wanna switch your route handlers place. Others wise you will never rich your api, as the first catches all request.
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}`);
});