res.json Nodejs/ Express

Asked

Viewed 1,393 times

1

I have a cruel doubt in nodejs/ Express, I am very new in language but what I need is to pass the id in a route to execute and return a query.

I’m wanting to do in fragmented files, so I have a Routes file (with all routes) an API file (where requests queries) and a Database file (where runs and returns all) 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 id does not execute id error, even I have tested and the ID is being passed, for example if I give a console.log(results) in the database file it logs me the query. My problem is sending this to the browser, because when I put res.json(results) he of 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!

  • 1

    Every time you call taskList.getTaskListById(id) you have to pass the res. I don’t think you should pass the res so for other functions. It is better to res be called with the result of the database in the module where flames taskList. Otherwise it is difficult to follow the logic of the application in my view.

  • 1

    Dude I can’t believe it was such a silly thing so HUAUAUHAHUAUH serio kkkkkkkkkkkkk I broke my head all day to fix it, but it was worth it, but the idea is to segment even more Apis so this separation will be useful, thank you very much put face there for me to score as right.

1 answer

1


Every time you call taskList.getTaskListById(id) you have to pass the res.

But I don’t think you should pass the res so for other functions. It is better to res be called with the result of the database in the module where flames taskList. Otherwise it is difficult to follow the logic of the application in my view.

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 being:

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

Browser other questions tagged

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