我正在尝试设置我的 Node 服务器/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);
关于javascript - Router.use() 需要中间件功能但未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28549833/
我正在尝试设置一个puppet节点,但rubygems似乎不正常。如果我通过它自己的二进制文件(/usr/lib/ruby/gems/1.8/gems/facter-1.5.8/bin/facter)在cli上运行facter,它工作正常,但如果我通过由rubygems(/usr/bin/facter)安装的二进制文件,它抛出:/usr/lib/ruby/1.8/facter/uptime.rb:11:undefinedmethod`get_uptime'forFacter::Util::Uptime:Module(NoMethodError)from/usr/lib/ruby
当我使用Bundler时,是否需要在我的Gemfile中将其列为依赖项?毕竟,我的代码中有些地方需要它。例如,当我进行Bundler设置时:require"bundler/setup" 最佳答案 没有。您可以尝试,但首先您必须用鞋带将自己抬离地面。 关于ruby-我需要将Bundler本身添加到Gemfile中吗?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/4758609/
我在我的项目中添加了一个系统来重置用户密码并通过电子邮件将密码发送给他,以防他忘记密码。昨天它运行良好(当我实现它时)。当我今天尝试启动服务器时,出现以下错误。=>BootingWEBrick=>Rails3.2.1applicationstartingindevelopmentonhttp://0.0.0.0:3000=>Callwith-dtodetach=>Ctrl-CtoshutdownserverExiting/Users/vinayshenoy/.rvm/gems/ruby-1.9.3-p0/gems/actionmailer-3.2.1/lib/action_mailer
刚入门rails,开始慢慢理解。有人可以解释或给我一些关于在application_controller中编码的好处或时间和原因的想法吗?有哪些用例。您如何为Rails应用程序使用应用程序Controller?我不想在那里放太多代码,因为据我了解,每个请求都会调用此Controller。这是真的? 最佳答案 ApplicationController实际上是您应用程序中的每个其他Controller都将从中继承的类(尽管这不是强制性的)。我同意不要用太多代码弄乱它并保持干净整洁的态度,尽管在某些情况下ApplicationContr
我已经从我的命令行中获得了一切,所以我可以运行rubymyfile并且它可以正常工作。但是当我尝试从sublime中运行它时,我得到了undefinedmethod`require_relative'formain:Object有人知道我的sublime设置中缺少什么吗?我正在使用OSX并安装了rvm。 最佳答案 或者,您可以只使用“require”,它应该可以正常工作。我认为“require_relative”仅适用于ruby1.9+ 关于ruby-主要:Objectwhenrun
我注意到像bundler这样的项目在每个specfile中执行requirespec_helper我还注意到rspec使用选项--require,它允许您在引导rspec时要求一个文件。您还可以将其添加到.rspec文件中,因此只要您运行不带参数的rspec就会添加它。使用上述方法有什么缺点可以解释为什么像bundler这样的项目选择在每个规范文件中都需要spec_helper吗? 最佳答案 我不在Bundler上工作,所以我不能直接谈论他们的做法。并非所有项目都checkin.rspec文件。原因是这个文件,通常按照当前的惯例,只
我实际上是在尝试使用RVM在我的OSX10.7.5上更新ruby,并在输入以下命令后:rvminstallruby我得到了以下回复:Searchingforbinaryrubies,thismighttakesometime.Checkingrequirementsforosx.Installingrequirementsforosx.Updatingsystem.......Errorrunning'requirements_osx_brew_update_systemruby-2.0.0-p247',pleaseread/Users/username/.rvm/log/138121
我想学习一些关于Continuation的知识,使用callcc方法从一些文章中键入几个示例,但我遇到了错误:NoMethodError:undefinedmethod`callcc'formain:Objectfrom(pry):2:in`'没有文章提到包含延续库。那么如何解决这个问题呢?谢谢编辑:ruby1.9.2p290(2011-07-09修订版32553)[x86_64-linux] 最佳答案 您需要要求“继续”。require'continuation' 关于ruby-继续,
这个问题在这里已经有了答案:关闭10年前。PossibleDuplicate:Rubysyntaxquestion:Rational(a,b)andRational.new!(a,b)我正在阅读ruby镐书,我对创建有理数的语法感到困惑。Rational(3,4)*Rational(1,2)产生=>3/8为什么Rational不需要new方法(我还注意到例如我可以在没有new方法的情况下创建字符串)?
我正在开发我的第一个Rubygem,并捆绑了cucumber、rspec和shoulda-matches进行测试。当我运行rspec时,出现以下错误:/app/my_gem/spec/spec_helper.rb:6:in`':undefinedmethod`configure'forShoulda::Matchers:Module(NoMethodError)这是我的gem规范:#my_gem.gemspec...Gem::Specification.newdo|spec|......spec.add_development_dependency"activemodel"spec.a