Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

285
Views
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.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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()
    }
   )}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!