Prabir Choudhury
Prabir Choudhury

Reputation: 236

TypeError: Router.use() requires a middleware function but got a Object[using express router] --

The app, I am building with nodeJS expressJS is for connecting to a sqlserver database and retrieving data. Am trying to make the code as modular and reusable as posssible. So different files for routing and controller. The error I am now facing is-

throw new TypeError('Router.use() requires a middleware function but got a ' + gettype(fn))
      ^

TypeError: Router.use() requires a middleware function but got a Object

For ease of understanding of the imports, my project structure is as such:

controller
    |-- controller.js
db
    |-- db.js
query
    |-- queries.json
routes
    |-- route.js
package.json
server.js

My main server.js file is

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=require('./routes/route');
const app = express()

app.use(cors());

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

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

app.use(morgan('dev'));

const port = 3200

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

the controller file is

const express=require('express')

const { sql, poolPromise } = require('../db/db')
const fs = require('fs');


class MainController
{
    async getAllData(req, resp)
    {
        try 
        {
            const pool = await poolPromise
            const result = await pool.request()
            .query("select * from players");
            resp.json(result.recordset)
        }
        catch (error)
        {
            resp.status(500)
            resp.send(error.message)
        }
    }

}

const controller=new MainController();
module.exports=controller;

and the route file is

const express =  require('express');
const controller = require('../controller/controller')

const router = express.Router();

router.get('/getAllData', controller.getAllData);

So when I insert this line app.use('api/', router) in the server.js to wire all the modules together and make calls to api endpoint to get all data, I am getting that error mentioned.

What is it about, can anyone explain me in simple terms? Is the error being thrown from the controller file, since I am initializing a new instance of the controller type? Which line from which file is throwing this error? What is the code correction needed to remove this error?

Upvotes: 0

Views: 1473

Answers (2)

Ali Iqbal
Ali Iqbal

Reputation: 372

Try out one of these:

1- if your are using express and doing

const router = express.Router();

make sure to

module.exports = router ;

at the end of your page

2- If your are using express above 2.x, you have to declare app.router like below code. Please try to replace your code

app.use('/', routes);

with

app.use(app.router);
routes.initialize(app);

Upvotes: 0

Nabhag Motivaras
Nabhag Motivaras

Reputation: 134

under route.js change to router.get('/getAllData', controller.getAllData()); you have passed controller.getAllData as a handler function instead of controller.getAllData() as per the type of method you have used in class. hope this solves the error.

Upvotes: 1

Related Questions