res.json NodeJS / Express

1

I have a cruel doubt on nodeJs / Express, I'm pretty new to the language but what I need is to pass the id on a route so that it executes and returns a query.

I want to do in fragmented files, so I have a Routes file (with all routes) an API file (where you request the queries) and a Database file (where it executes and returns everything) the code is below:

Routes:

const express= require('express')

module.exports = function (server) {

  const router = express.Router()
  server.use('/api',router)

  const taskList = require('../api/taskList/taskList')
  router.route('/taskList').get(taskList.getTaskList)

  router.get('/taskList/:id?',(req,res) =>{
    if(req.params.id) id = parseInt(req.params.id)
    return taskList.getTaskListById(id)
  })


}

API:

const con = require('../../config/database')

//console.log(con.connectionCheck())
function getTaskList(req,res){
  return con.query('SELECT * FROM TB_TASKLIST',res)
}

function getTaskListById(id,res){
  //return console.log(id)
    return con.queryById('SELECT * FROM TB_TASKLIST WHERE COD_ID_USER_TASK_LIST like ${id}',res)
    console.log(res)
}

module.exports = {getTaskList,getTaskListById}

Database:

const mysql = require('mysql')
const connection = mysql.createConnection({
  host : 'localhost',
  port: 3306,
  user:'root',
  password:'',
  database:'db_lifeapp'
})


function connectionCheck(){
  connection.connect(function(err) {
    if(err) console.log(err)
    console.log("conectado")
  })
}

function query(sqlQry,res){
  connection.query(sqlQry,function (err,results,fields) {
    if(err){
      res.json(err)
    }else{
      res.json(results)
      console.log("Query Executada")
    }
  })
}

function queryById(sqlQry,res){
  connection.query(sqlQry,function (err,results,fields) {
    if(err){
      console.log(err)
    }else{
      console.log("executado")
      res.json(results)
    }
  })
}

module.exports = {connectionCheck,query,queryById}

The first query where I do not do id executes without error, I have already tried it and the ID is being passed, for example if I give console.log(results) in the database file it logs me a query. My problem is being send this to the browser, because when I put res.json(results) it from error:

C:\Users\felipe.sangiorge\Desktop\ProjetoAPP\Backend\node_modules\mysql\lib\protocol\Parser.js:80
        throw err; // Rethrow non-MySQL errors
        ^

TypeError: Cannot read property 'json' of undefined
    at Query._callback (C:\Users\felipe.sangiorge\Desktop\ProjetoAPP\Backend\config\database.js:35:10)
    at Query.Sequence.end (C:\Users\felipe.sangiorge\Desktop\ProjetoAPP\Backend\node_modules\mysql\lib\protocol\sequences\Sequence.js:88:24)
    at Query._handleFinalResultPacket (C:\Users\felipe.sangiorge\Desktop\ProjetoAPP\Backend\node_modules\mysql\lib\protocol\sequences\Query.js:139:8)
    at Query.EofPacket (C:\Users\felipe.sangiorge\Desktop\ProjetoAPP\Backend\node_modules\mysql\lib\protocol\sequences\Query.js:123:8)
    at Protocol._parsePacket (C:\Users\felipe.sangiorge\Desktop\ProjetoAPP\Backend\node_modules\mysql\lib\protocol\Protocol.js:279:23)
    at Parser.write (C:\Users\felipe.sangiorge\Desktop\ProjetoAPP\Backend\node_modules\mysql\lib\protocol\Parser.js:76:12)
    at Protocol.write (C:\Users\felipe.sangiorge\Desktop\ProjetoAPP\Backend\node_modules\mysql\lib\protocol\Protocol.js:39:16)
    at Socket.<anonymous> (C:\Users\felipe.sangiorge\Desktop\ProjetoAPP\Backend\node_modules\mysql\lib\Connection.js:103:28)
    at emitOne (events.js:96:13)
    at Socket.emit (events.js:188:7)

Thank you in advance for any help Thank you!

    
asked by anonymous 06.10.2017 / 22:27

1 answer

1

Whenever you call taskList.getTaskListById(id) you have to pass res .

But I do not think you should pass res to other functions as well. It is best that res be called with the result of the database in the module where you call taskList . Otherwise it is difficult to follow the logic of the application as I see it.

For example:

router.get('/taskList/:id?', (req, res) =>{
    if(req.params.id) id = parseInt(req.params.id)
    taskList.getTaskListById(id).then(data => res.json(data));
})

and the API is:

function query(sqlQry, res) {
    return new Promise(function(resolve, reject) {
        connection.query(sqlQry, function(err, results, fields) {
            if (err) reject(err);
            else resolve(results);
        });
    });
}
    
06.10.2017 / 22:52