Mehdavi5 Mehdavi5 - 7 months ago 47
Node.js Question

TypeError: Router.use() requires middleware function

I am developing a REST API through node using express. When I try to run my application, I get this error:


TypeError: Router.use() requires middleware function but got a Object
at Function.use (/Users/....../Desktop/NodeProjects/MyWebsite/node_modules/express/lib/router/index.js:458:13)
at EventEmitter.<anonymous> (/Users/......./Desktop/NodeProjects/MyWebsite/node_modules/express/lib/application.js:219:21)
at Array.forEach (native)
at EventEmitter.use (/Users/........./Desktop/NodeProjects/MyWebsite/node_modules/express/lib/application.js:216:7)
at Object.<anonymous> (/Users/............./Desktop/NodeProjects/MyWebsite/app.js:32:5)
at Module._compile (module.js:398:26)
at Object.Module._extensions..js (module.js:405:10)
at Module.load (module.js:344:32)
at Function.Module._load (module.js:301:12)
at Function.Module.runMain (module.js:430:10)



Below is my code:

app.js
Code

var express = require('express');
var http = require('http');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var nodemailer = require('nodemailer');
var url = require('url');

var routes = require('./routes/index');
var contacts = require('./routes/contacts');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.set('port', process.env.PORT || 3000);

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/contacts', contacts);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});

app.get('/contacts',function(request, response){
var get_params = url.parse(request.url, true).query;
if (Object.keys(get_params).length == 0)
{
response.setHeader('content-type', 'application/json');
response.end(JSON.stringify(contacts.list()));
}
else
{
response.setHeader('content-type', 'application/json');
stringify(contacts.query_by_arg(get_params.arg, get_params.value));
}
});


http.createServer(app).listen(app.get('port'), function() {
console.log('Express server listening on port ' + app.get('port'));
});


module.exports = app;


Code of
Contacts.js


var fs = require('fs');

//Read Json file
function read_json_file() {
var file = './data/contacts.json';
return fs.readFileSync(file);
}

//Parse the the file da
exports.list = function() {
return JSON.parse(read_json_file());
};

exports.query = function(number) {
var json_result = JSON.parse(read_json_file());
var result = json_result.result;
for (var i = 0; i < result.length; i++) {
var contact = result[i];
if (contact.primarycontactnumber === number) {
return contact;
}
}
return null;
};

exports.query_by_arg = function(arg, value) {
var json_result = JSON.parse(read_json_file());
var result = json_result.result;
for (var i = 0; i < result.length; i++) {
var contact = result[i];
if (contact[arg] === value) {
return contact;
}
}
return null;
};

exports.list_groups = function() {
var json_result = JSON.parse(read_json_file());
var result = json_result.result;
var resultArray = [];
for (var i = 0; i < result.length; i++) {
var groups = result[i].groups;
for (var index = 0; index < groups.length; index++) {
if (resultArray.indexOf(groups[index]) === -1) {
resultArray.push(groups[index]);
}
}
}
return resultArray;
};

exports.get_members = function(group_name) {
var json_result = JSON.parse(read_json_file());
var result = json_result.result;
var resultArray = [];
for (var i = 0; i < result.length; i++) {
if (result[i].groups.indexOf(group_name) > -1) {
resultArray.push(result[i]);
}
}
return resultArray;
};


When I comment out the
app.use('/contacts', contacts);
line in my
app.js
then it works fine. Otherwise I get this issue. I have tried a lot to dig into the reason behind it but have failed. Can any one help me with this please.

Answer

As per the docs, app.use is for registering middleware; your contacts.js doesn't contain any middleware, it just contains the helper functions you use inside the actual /contacts route.

As you noted, commenting it out makes everything work just fine. There's no need to do anything else :)

You'll also want to move your 404 handler after your routes, otherwise it'll be run before every route, hence the 404s you see. See the error handling docs for more info.