Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

299
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda