与Express结合
module_users = require './routes/module_users.coffee'
app.get 'users',module_users.list
流程很简单
引用模块文件
调用模块文件中的方法,前提是你要将方法输出,请参见下面的引用
测试
Controller控制器
Express路由原理
在app.coffee文件中定义路径,添加引用
index = require './routes/index.coffee' app.get 'index',index.list在routes/index.coffee中定义方法,输出引用
list=(req,res)-> res.render 'index',{title:"Hello Express"} module.exports.list = list这样实现了Controller和Module之间的双向通信
其中req是http请求,res是http回应,具体可参考Express手册中文版
常用的Express API
req.body
这个对应的是解析过的请求体。这个特性是
bodyParser()中间件提供,其它的请求体解析中间件可以放在这个中间件之后。当bodyParser()中间件使用后,这个对象默认为 {}。// POST user[name]=tobi&user[email][email protected] req.body.user.name // => "tobi"req.params
这是一个数组对象,命名过的参数会以键值对的形式存放。 比如你有一个路由
/user/:name,"name"属性会存放在req.params.name. 这个对象默认为{}.// GET /user/tj req.params.name // => "tj"res.render(view, [locals], callback)
渲染view, 同时向callback 传入渲染后的字符串。 callback如果不传的话,直接会把渲染后的字符串输出至请求方, 一般如果不需要再对渲染后的模板作操作,就不需要传callback。 当有错误发生时next(err)会被执行. 如果提供了callback参数,可能发生的错误和渲染的字符串都会被当作参数传入, 并且没有默认响应。
res.render 'index', (err, html)-> console.log "index.html" res.render 'user', { name: 'Tobi' }Javascript的模块输出和引用
需要使用module.exports方法
list=(req,res)-> Users.list (err, user)- > console.log(err, user.id) module.exports.list = list这样你的list函数可以被其它文件引用了
有时候可以更加简化
module.exports.list=(req,res)-> Users.list (err, users)- > console.log(err)