Request for the Nodejs API

Asked

Viewed 61 times

1

I’m trying to make an appointment of only 1 id and he returns to me an empty object.

If I put localhost:8877/jogador/2, return on console is empty.

If I put localhost:8877/jogador/1, he returns me all the bank records.

What’s wrong with my Controller?

// LISTAR TODOS OS JOGADORES
listJogadores(request, response) {
    database.select("*").table("jogadores").then(apelido => {
        console.log(apelido);
        response.json(apelido);
    }).catch(error => {
        console.log(error)
    })
}

// LISTAR APENAS 1 JOGADOR
listUmJogador(request, response) {
    const id = request.params

    database.select("*").table("jogadores").where({ id: id }).then(apelido => {
        response.json(apelido)
    }).catch(error => {
        console.log(error)
    })
}

Route archive:

router.get('/jogador', JogadorController.listJogadores);    
router.get('/jogador/:id', JogadorController.listUmJogador);

I’m using express and Xios.

  • "If I place localhost:8877/1" missed "gambler" en route?

  • I edited, kkkk. But that’s it...

  • If I place the host/player/1 it returns all registered players.

2 answers

4


Starting from the point you are using Express, your problem there is that req.params as you can see in the documentation, returns an object containing properties mapped to the "parameters" of the named route. That is, when you do this:

const id = request.params

The constant id is storing the object params and not a unique value, in which case your id. What would require you to do this to get the id value:

.where({ id: id.id }) // aqui está acessando a propriedade id armazenada em id

The correct thing would be to take the property you want and store it in the constant:

const id = request.params.id; // pega a parametro com nome id
.where({ id: id })

2

Missing pass id to variable.

If you were using an older version of nodejs it would be:

listUmJogador(request, response) {
    const id = request.params.id //adicionar este .id

    database.select("*").table("jogadores").where({ id: id }).then(apelido => {
        response.json(apelido)
    }).catch(error => {
        console.log(error)
    })
}

or make a atribuição por desestruturação:

listUmJogador(request, response) {
    const { id } = request.params

    database.select("*").table("jogadores").where({ id: id }).then(apelido => {
        response.json(apelido)
    }).catch(error => {
        console.log(error)
    })
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.