16

I am trying to set up my node server / REST api.

For this i have a few different files:

division_model.js:

 module.exports = function(express, sequelize) { var router = express.Router(); router.route('/division'); var DataTypes = require("sequelize"); var Division = sequelize.define('division', { id: DataTypes.INTEGER, organization_id: DataTypes.INTEGER, location_id: DataTypes.INTEGER, name: DataTypes.STRING, parent_id: DataTypes.INTEGER }, { freezeTableName: true, instanceMethods: { retrieveAll: function (onSuccess, onError) { Division.findAll({}, {raw: true}) .ok(onSuccess).error(onError); }, retrieveById: function (user_id, onSuccess, onError) { Division.find({where: {id: user_id}}, {raw: true}) .success(onSuccess).error(onError); }, add: function (onSuccess, onError) { var username = this.username; var password = this.password; var shasum = crypto.createHash('sha1'); shasum.update(password); password = shasum.digest('hex'); Division.build({username: username, password: password}) .save().ok(onSuccess).error(onError); }, updateById: function (user_id, onSuccess, onError) { var id = user_id; var username = this.username; var password = this.password; var shasum = crypto.createHash('sha1'); shasum.update(password); password = shasum.digest('hex'); Division.update({username: username, password: password}, {where: {id: id}}) .success(onSuccess).error(onError); }, removeById: function (user_id, onSuccess, onError) { Division.destroy({where: {id: user_id}}).success(onSuccess).error(onError); } } } ); // on routes that end in /users/:user_id // ---------------------------------------------------- router.route('/division/:division_id') // update a user (accessed at PUT http://localhost:8080/api/users/:user_id) .put(function (req, res) { var user = User.build(); Division.username = req.body.username; Division.password = req.body.password; Division.updateById(req.params.division_id, function (success) { console.log(success); if (success) { res.json({message: 'User updated!'}); } else { res.send(401, "User not found"); } }, function (error) { res.send("User not found"); }); }) // get a user by id(accessed at GET http://localhost:8080/api/users/:user_id) .get(function (req, res) { var Division = Division.build(); Division.retrieveById(req.params.division_id, function (users) { if (users) { res.json(users); } else { res.status(401).send("User not found"); } }, function (error) { res.send("User not found"); }); }) // delete a user by id (accessed at DELETE http://localhost:8080/api/users/:user_id) .delete(function (req, res) { var division = Division.build(); division.removeById(req.params.division_id, function (users) { if (users) { res.json({message: 'User removed!'}); } else { res.status(401).send("User not found"); } }, function (error) { res.send("User not found"); }); }); }; 

And my server.js

 // BASE SETUP // ============================================================================= var express = require('express'), bodyParser = require('body-parser'); var app = express(); var router = express.Router(); var es = require('express-sequelize'); // ============================================================================= // IMPORT MODELS // ============================================================================= app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); var env = app.get('env') == 'development' ? 'dev' : app.get('env'); var port = process.env.PORT || 8080; var Sequelize = require('sequelize'); // db config var env = "dev"; var config = require('./database.json')[env]; var password = config.password ? config.password : null; // initialize database connection var sequelize = new Sequelize( config.database, config.user, config.password, { logging: console.log, define: { timestamps: false } } ); //================================================================================ var division_model = require('./Divisions/division_model')(express,sequelize, router); app.use('/division', division_model); // REGISTER ROUTES // ============================================================================= app.use('/api', app.router); // START THE SERVER // ============================================================================= app.listen(port); console.log('Magic happens on port ' + port); 

However with this i get the following error message when starting the server:

 throw new TypeError('Router.use() requires middleware function but got a ^ TypeError: Router.use() requires middleware function but got a undefined at Function.<anonymous> (/var/www/example/backend/node_modules/express/lib/router/index.js:446:13) at Array.forEach (native) at Function.use (/var/www/example/backend/node_modules/express/lib/router/index.js:444:13) at EventEmitter.<anonymous> (/var/www/example/backend/node_modules/express/lib/application.js:187:21) at Array.forEach (native) at EventEmitter.use (/var/www/example/backend/node_modules/express/lib/application.js:184:7) at Object.<anonymous> (/var/www/example/backend/server.js:42:5) at Module._compile (module.js:456:26) at Object.Module._extensions..js (module.js:474:10) at Module.load (module.js:356:32) 

Can anyone tell me why this is happening?

2 Answers 2

33

You must return a router in your middleware here:

app.use('/division', division_model); 

So, your module export function should end with:

return router; 

You also have conflicting ideas when setting this up. If you want the app to define the route as /division which you do here:

app.use('/division', division_model); 

then you do not need to redefine the route again like you do here:

var router = express.Router(); router.route('/division'); 

You can simply:

app.use(division_model); 

-- or --

/** * division_model.js */ var router = express.Router(); router.route('/'); //omitting route code router.route('/:division_id'); //omitting route code return router; /** * server.js */ app.use('/division', division_model); 
Sign up to request clarification or add additional context in comments.

3 Comments

The thing you said in the middle with conflicting ideas which one is prefered to use?
also this removed the error however whenever i call the server i get: Cannot GET /api/division However /api/division/31 works ????
Your implementation is completely up to you, I personally like to let app.use handle the actual endpoint, and define my subroutes without prefixing with the route name. The reason /api/division does not work, is because you actually never defined anything for it. The only routes you defined were for /api/division/:id. If you want a default route at /api/division you need to do it the way you did the other ones: router.route('/division').get(function(req, res) { return res.send('hello world'); })
1

because you are exporting module with a function inside so you need to return your router at the end of your function at division_model.js

return router; 

this should work

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.