'router.get doesn't work but router.get with id works
calling http://localhost:5000/surveycreate/4 works and redirects me to surveypage.html
but calling http://localhost:5000/surveycreate does not work, it redirects me my my main index.js file in public folder it doesn't even print "regular get"
why is this happening?
surveypage.js in route
const path = require("path");
const router = express.Router();
router.use(express.static(path.join(__dirname, "../public")));
router.get('/:id', async (req, res) => {
console.log("get with id");
res.sendFile(path.join(__dirname, "../public/Surveypage.html"));
})
router.get('/', async (req, res) => {
console.log("regular get");
res.sendFile(path.join(__dirname, "../public/Surveypage.html"));
})
module.exports = router; ```
==============================================================================
index.js of node:
const surveyPage = require('./routes/surveypage')
const app = express();
app.use(express.json());
app.use('/surveypage',surveyPage)
app.use(express.static(path.join(__dirname, "/public")));
app.use(cors())
const PORT = process.env.PORT || 5000
app.listen(PORT , () => {
console.log(`Listenning on porst ${PORT }`);
})
Solution 1:[1]
Make sure the structure of your files correspond with your code.
The following code is working well for me:
app.js:
const express = require("express");
const app = express();
const cors = require("cors")
const surveyPage = require('./routes/surveypage')
const path = require("path");
const PORT = process.env.PORT || 5000
app.use(express.json());
app.use('/surveypage', surveyPage)
//app.use(express.static(path.join(__dirname, "/public"))); // not needed
app.use(cors())
app.listen(PORT, () => console.log(`Listenning on porst ${PORT }`))
surveypage.js
const path = require("path");
const express = require('express')
const router = express.Router();
router.use(express.static(path.join(__dirname, "../public")));
router.get('/:id', (req, res) => res.sendFile(path.join(__dirname, "../public/Surveypage.html")));
router.get('/', (req, res) => res.sendFile(path.join(__dirname, "../public/Surveypage.html")))
module.exports = router;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Rafi Henig |