I have URL like this : http://localhost:3000/pageName and I am setting my express route like below:
app.get("/:pageName",(req,res)=>{
if (authentication === true) {
res.render(req.param.pageName}
})
Above works fine when it gets http://localhost:3000/demo.
However, when it gets this type of URL : http://localhost:3000/pageName/authToken like:
http://localhost:3000/demo/ubawfei346876jhat78gw8898ig8837yr
Route says cannot get demo/ubawfei346876jhat78gw8898ig8837yr and when I changed above code to this :
app.get("/:pageName/: authToken",(req,res) => {
if(authentication===true{
res.render(req.param.pageName}
)}
Then this type of url works fine :
http://localhost:3000/demo/ubawfei346876jhat78gw8898ig8837yr
But this type of URL : http://localhost:3000/demo is not working anymore
I would like to implement something like this when url is something like this
http://localhost:3000/demo then it should redirect to:
req.params.pageName
And when url looks like this http://localhost:3000/demo/yeieyhsi736hdh then it should varify token if varified redirect to:
req.params.pageName
You can implement both routes, and if an authToken is provided, then run a check on the authToken.
However, the way you are doing it right now would cause an endless redirect, as when any request to your /:pageName is made, it would be redirected to itself, so you need to provide a response with your content from within the route, not a redirect.
app.get("/:pageName", (req, res) => {
if (authentication) {
let pageName = req.params.pageName;
//Retrieve something with pageName and send it;
res.send(pageName);
} else {
res.send("Not authorised");
}
})
app.get("/:pageName/:authToken", (req, res) => {
let authToken = req.params.authToken;
if (isGood(authToken) && authentication) { //Fictious authToken check
let pageName = req.params.pageName;
//Retrieve something with pageName and send it;
res.send(pageName);
} else {
res.send("Not authorised");
}
})
Make your url like this http://localhost:3000/demo?token=As3ferrfmi5jr4jr4btdth54y6y6rty34t45t5y666666
app.get('/:pageName', (req, res) => {
//you can check if pageName is correct or not
if (req.query.token != undefined) {
const token = req.query.token;
// we must use strong secret, I am using "secret" for demo
jwt.verify(token,"secret", (err,data) => {
if (err) {
//do something if error occurs
} else {
// you can also do something with data which was stored on your token
res.render(req.params.pageName);
}
})
} else if (authenticate) {
// do something for authentication to access this else if
res.render(req.params.pageName);
} else {
// you can also render some error page or send 404 status
res.send('Something went wrong!');
}
});