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

80
Visualizações
NodeJS Express: I have two app.get requests and they blend together

So I have 1 request that is

app.get('/assignment/loans', (req, res) => { 
    const id = req.query.bookID;
}

and another that is this:

app.get('/assignment/loans', (req, res) => {
    const id = req.query.studentID;
}

For some reason, the studentID one does not work and it always goes to the bookID to search. I use this

http://localhost:3000/assignment/loans?bookID=1

and it works as intended but if I use

http://localhost:3000/assignment/loans?studentID=9653

I get:

enter image description here

which is an error that should only appear for the bookID. How can I differentiate the two? Thank you in advance.

More code regarding the two requests: https://pastebin.com/1A0jK3BX

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

You cannot have 2 routes with same url. first one take precedence. You need to handle it like this.

app.get('/assignment/loans', (req, res) => { 
   const bookID = req.query.bookID;
   const studentID = req.query.studentID;
   if(bookID){
   }
   if(studentID){
   }

}
about 4 years ago · Juan Pablo Isaza Relatório

0

actually express framework will execute the first endpoint when request happened which is

app.get('/assignment/loans', (req, res) => { const id = req.query.bookID;})

in duplicated endpoint case, so you should using one route and put tow queries instead of one so the code will be like this

app.get('/assignment/loans', (req, res) => { 
const book_id = req.query.bookID;
const student_id = req.query.studentID
})
  

also you have to make validation for queries before executed in db

about 4 years ago · Juan Pablo Isaza Relatório

0

You have exact same routes

app.get('/assignment/loans', ...) it has to be one route.

Try combining em like this below

app.get('/assignment/loans', (req, res) => {
  const bookId = req.query.bookID;
  const studentId = req.query.studentID;
  const loans = [];

  if(bookId){
    if(!Number.isInteger(parseInt(studentId))){
      return res.status(422)
        .setHeader('content-type', 'application/json')
        .send({error: 'bookId not numeric'});
    }
    db.all('SELECT * FROM loan WHERE bookID=?', bookId, (err, rows) => {
      if (err) {
        res.status(422)
          .setHeader('content-type', 'application/json')
          .send({error: 'Problem while querying database'});
        return;
      }
      if (rows.length === 0) {
        res.status(404)
          .setHeader('content-type', 'application/json')
          .send({error: 'loan bookId was not found!'});
      } else {
        rows.forEach(row =>
          loans.push({id: `${row.id}`, bookID: `${row.bookID}`}));
        res.status(200)
          .setHeader('content-type', 'application/json')
          .send(loans);
      }
    });
  }else if(studentId){
    if(!Number.isInteger(parseInt(studentId))){
      return res.status(422)
        .setHeader('content-type', 'application/json')
        .send({error: 'studentId not numeric'});
    }
    db.all('SELECT * FROM loan WHERE studentID=?', studentId, (err, rows) => {
      if (err) {
        return res.status(422)
          .setHeader('content-type', 'application/json')
          .send({error: 'Problem while querying database'});
      }
      if (rows.length === 0) {
        res.status(404)
          .setHeader('content-type', 'application/json')
          .send({error: 'loan studentId was not found!'});
      } else {
        rows.forEach(row =>
          loans.push({id: `${row.id}`, studentID: `${row.studentID}`}));
        res.status(200)
          .setHeader('content-type', 'application/json')
          .send(loans);
      }
    });
  }else{
    return res.status(400)
      .setHeader('content-type', 'application/json')
      .send({error: 'Please provide required query string'});
  }
});
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