I connected the database to the project in node js and the connection works without a problem, but when I try to retrieve the data using the get operation, an error occurs that I could not solve
sql connection
const mysql = require("mysql");
const connection = mysql.createConnection({
host: "localhost",
user: "root",
password: "my password",
database: "test"
});
connection.connect(function (err) {
if (err) throw err
console.log("connection");
})
module.exports = { connection }
Request from the page
const express = require("express");
const {connection} = require('../../dbConected')
const router = express.Router();
const {
getallstudents
} = require('../controllers/student')
router.get("/", getallstudents)
module.exports = router;
controllers
const {connection} = require('../../dbConected')
module.exports = {
getallstudents:
connection.query("SELECT * FROM test.student",function (err,result){
if (err) throw err;
console.log(result);
})
}
the error
Route.get() requires a callback function but got a [object Object]
and
[nodemon] app crashed – waiting for file changes before starting…Thanks for the helpers
3
Answers
And I get an error in the json file the err
"message": "Converting circular structure to JSONn --> starting at object with constructor 'Query'n | property '_timer' -> object with constructor 'Timer'n --- property '_object' closes the circle"
and GET /getallstudents 500 2.939 ms - 224
Main issue here is the router.get requires a function but in example there is a object instead of it. So ‘getallstudents’ must be a function.
Change this to
You need to pass a callback which will be the controller for the
router.get
, RTM https://expressjs.com/en/guide/routing.htmlthen inside this code:
rather than doing
if (err) throw err; console.log(result);
, send the response back.or like:
..but what is
next(err)
, rtm: https://expressjs.com/en/guide/error-handling.html#writing-error-handlers