Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Not able to do get request using global variable in Node js and Express

this is a small code from my index.js file in backend:

var topic = "";

app.post(`/posts`,(req,res)=>{
    topic = req.body.ReadMore;
    res.redirect(`/posts/${topic}`);
});

app.get(`/posts/${topic}`, (req,res) => {
    res.render('page')
})

I am trying to change the value of variable topic and then I want to redirect to /posts/topic . However, I am getting this error : Cannot GET /posts/topicName (console is showing error 404). Why is this not working? Also if I just hard code the topicName to my get request
, for example,

 app.get('/posts/topicName', (req,res) => {
    res.render('page')
})

It works perfectly. But in my case, I have many topics which can be passed to the server and I need to render pages relevantly.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The /posts/${topic} is evaluated once. So if topic is an empty string, the middleware sees the value of the path as /posts/. Even if you change the value of the topic variable, the path is already set.

You can use this /post/:topic to have topic as a dynamic parameter for express. You can then use

const topic = "";
app.get(`/posts/:topic`, (req,res,next) => {
    const param_topic = req.params.topic;
    if (param_topic == topic) {
         // do something
    }
    else 
    {
         return next()
    }
   )}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading