Page with Nodejs with Mysql database

Asked

Viewed 692 times

0

I’m creating a API to then be consumed in React. In this API you will have a route(page) that will list database users.

I applied the rules and I’m testing in India, which by the way is working well.

My problem and when I leave the parameter of url emptiness, Example: localhost/user/.

I wish that when left empty returns the first page.

follows the code below:

 if(results){
        const numero_registros = results.length; // Existe 37 registros no banco
        let  pagina_atual = req.params.page || 1;
        let total_paginas = Math.ceil(numero_registros/10); 


            let count = (pagina_atual*10)-10;

            connection.query(`SELECT * FROM usuarios_homos LIMIT 10 OFFSET ${count}`,(err,result,fields)=>{
                if(err){
                    console.log(err);
                }else{
                    res.send(result);
                }

            });

Screenshot of the Insomnia showing the page: inserir a descrição da imagem aqui

Image of the beginning when I don’t pass the parameter inserir a descrição da imagem aqui

[PROBLEM SOLVED]

 // Páginação
    if(results){
        const rows = results.length; // Existe 37 registros no banco
        let { page = 1 } = req.query; // passando argumento pela url >> usuarios?page=1
        let calc = Math.ceil(rows/10); // calc recebe a quantidade de páginas existentes

        if(page == ''){
            page = 1;
        }

            let count = (page*10)-10;

        const qtd = connection.query(`SELECT * FROM usuarios_homos LIMIT 10 OFFSET ${count}`,(err,result,fields)=>{
                if(err){
                    console.log(err);
                }else{
                    res.send(result);
                }

            });

ON THE ROUTES BECAME:

router.get('/usuarios',queryController);
  • What happens when you do not pass the page by parameter in the url?

  • Return me in India 404 Not Found

  • As you stated the route in Node.js?

  • Put >> router.get( '/usuarios/:page', queryController);

  • Although the question has already been resolved, I recommend editing it to add the code of the route statement. It is important and can help people with the same problem in the future.

1 answer

1


Hello, all right?

If I understand what you want, is to create a way of when the user access the http://localhost:3010/usuarios direct paging automatically to page 1. Right?

Conceptualization:

For this, we will need to decouple your routes and use a very cool pattern known as middleware (that’s right, it is a program that runs in the middle of something offering an aid in some specific task, as the treatment of inputs for example).

Our middleware in this case, it will be built to handle the url before the user listing is accessed.

Hand on the code:

Well, I will set up from this the zero an express service and you take advantage of the parts that will add to your case, ok?

Creating index.js, server.js, or app.js

// Porta do serviço.
const port = 4000;

// Importação do módulo express.
const express = require('express');

// Criação da instância do serviço.
const app = express();

// Importação das nossa rotas desacopladas (falaremos delas mais tarde).
const routes = require('./routes');

// Aqui podemos ver a primeira forma de um middleware.
// Com o método "use" eu digo ao serviço que ele deve executar as rotas importadas
// somente se houver um prefixo "/usuarios" na url.
app.use('/usuarios', routes);

// Inicialização do serviço.
app.listen(port, () => console.log(`Running on ${port}...`));

Creating the Routes.js

const express = require('express');

// Criação de uma instância de roteador (router) do express.
const router = express.Router();

// Aqui temos mais um middleware, e esse é a estrela do nosso negócio.
// É ele quem vai verificar a url e tratar para depois chamar nossa rota de paginação.
router.use((req, res, next) => {

  // Se a url for igual a uma "/" pura, reset ela para "/1".
  if (req.url === '/') {
    req.url = '/1';
  }

  // Chamo o nosso next, ele quem vai fazer a próxima rota na fila ser executada.
  next();
});

// E finalmente nossa rota de listagem com toda lógica complexa.
router.get('/:page', (req, res) => {
  const page = req.params.page;

  res.send(`Página = ${page}`);
});

// Exportação do router para que possamos usar ele no index.js
module.exports = router;
  • 1

    Very good, very good indeed, but I did it another way using req.query as Rafael would have indicated me and finally managed to make the page. This form you used will be very useful for me because the code was very clean and easy to understand. I will save here as a second option.. thanks man!

Browser other questions tagged

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