Home > Software engineering >  Not able to do get request using global variable in Node js and Express
Not able to do get request using global variable in Node js and Express

Time:06-27

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.

CodePudding user response:

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()
    }
   )}
  • Related