Tuesday 25 June 2019

Empty response from mysql query - async callback question

I am writing a small app and trying to query all the users from my mysql database. I'm new to nodejs, express and mysql. I'm able to execute queries, but I am having trouble returning the value of the query to the browser as a json object, using postman.​Here is the code for my userRouter.js file:const usersRouter = require('express').Router(); const userController = require('./usersController');usersRouter.get('/', function(req, res, next) {var testObject = userController.getUsers();res.json(testObject);});module.exports = usersRouter;​And here is from the userController.js file:const db = require('../database/db'); exports.getUsers = function(callback){var allUsers = db.query('SELECT * FROM users', function (err, rows, fields) { if (!err) { if (rows) { callback(null, rows); console.log("userController.getAllUsers - completed query") } else { callback(err, null); console.logo("userController.getAllUsers - error performing query.") } }}) }I obviously get an error that says "callback is not a function"...The reason I have ... function(callback){ .... written like that is because that's what I"ve seen online in forums and answered questions. It doesn't make sense to me to just have "callback" defined as a function parameter, then called later in the function body because the function isn't defined, but nearly every example I see online on how to solve this problem writes the solution in this manner.​What is the smart way to return the response from the query? I know I need to "use a callback" function to do it, I just am not quite sure how.

Submitted June 26, 2019 at 12:25AM by f6engineer

No comments:

Post a Comment