0

My problem is as the title of the question is. I am trying to isolate the concerns in my node n express app into separate routes and controllers to keep main server.js file clean.

My project structure is as

controller
|---------- controller.js
database
|---------- db.js
route
|---------- players.js
package.json
|
server.js

My controller.js is as:

const {sql, poolPromise, config}=require('../database/db')
const msnodesqlv8=require('msnodesqlv8');


const getAllPlayers=async(req, res, next)=>
{
    try
    {
        sql.connect(config, function(err)
        {
            if(err)
            {
                console.log(err);
            }
            else
            {
                var request=new sql.Request();

                request.query("select * from players", function(err, recordset)
                {
                    if(err)
                    {
                        console.log("Error while querying: "+err)
                    }
                    else
                    {
                        res.send(recordset);
                    }
                });
            }
        });
        
    }
    catch(err)
    {
        res.status(400).send(error.message);
    }
}


module.exports={
    getAllPlayers
}

The routes file is:

const express=require('express');
const router=express.Router();
const playerControll=require('../controller/controller')

router.get('/players', playerControll.getAllPlayers());


module.exports={
    routes: router
}

My main server.js file as:

const express = require('express')

const bodyParser = require('body-parser')
const cors = require('cors')
const fs = require('fs')
const path = require('path')
const morgan = require('morgan')
const router=express.Router()
const app = express()
const {poolPromise, config, sql}=require('./database/db')
const playerRoutes=require('./route/players');

app.use(cors())

app.use(bodyParser.urlencoded({ extended: false }))

// parse application/json
app.use(bodyParser.json())

app.use('/api/v1', playerRoutes); <---- attaching to the route file

app.use(morgan('dev'))

app.use(router)

const port=3200;

app.listen(process.env.PORT || port , (err) => {
    if(err)
  console.log('Unable to start the server!')
  else
  console.log('Server started running on : ' + port)
  })

On running my app and executing the route localhost:3200/api/v1/players I am getting the error Error: Route.get() requires a callback function but got a [object Promise] at Route

Where does this point to? Which file? Can you steer me in the correct direction and help me line up the concerns controller and events properly so that the route /api/v1/players works properly and fetches data. Need help on this. I am unable to decipher the error message. Which object? Need assistance in rectifying the code. I am a complete newbie in node and express and in most glitches like this one I am all at sea.

Thanks

Prabir Choudhury
  • 143
  • 1
  • 18

0 Answers0