ノードサーバーをセットアップしようとしています/ REST api。
このために私はいくつかの異なるファイルを持っています:
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");
});
});
};
そして私の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);
ただし、これを使用すると、サーバーの起動時に次のエラーメッセージが表示されます。
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)
なぜこれが起こっているのか誰かに教えてもらえますか?
ここでミドルウェアのルーターを返す必要があります。
app.use('/division', division_model);
したがって、モジュールエクスポート関数は次のように終了する必要があります。
return router;
これを設定するときにも、矛盾する考えがあります。アプリでルートを/ divisionとして定義する場合は、次のようにします。
app.use('/division', division_model);
この場合、ここで行うようにルートを再定義する必要はありません。
var router = express.Router();
router.route('/division');
あなたは簡単にできます:
app.use(division_model);
-または-
/**
* 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);
内部に関数を含むモジュールをエクスポートしているため、関数の最後でルーターを返す必要がありますdivision_model.js
return router;
これはうまくいくはずです