如何在Lapis中响应POST,GET方法
by 糖果
How do I respond to GET, POST, DELETE or other HTTP verbs?
如何响应GET,, POST, DELETE等动作。The respond_to action decorator function gives a basic framework for running different code depending on the HTTP method.
在同一个路由中响应类似get,post这种用户请求,关键是要使用respond_to这个装饰器。
try_to_login is a hypothetical functions, and not regularly globally available
try_to_login,只是一个假的,用说明可能会调用的驱动函数。
local lapis = require("lapis")
local app = lapis.Application()
local respond_to = require("lapis.application").respond_to
app:match("/", respond_to({
-- do common setup
before = function(self)
if self.session.current_user then
self:write({ redirect_to = "/" })
end
end,
-- render the view
GET = function(self)
return { render = true }
end,
-- handle the form submission
POST = function(self)
self.session.current_user =
try_to_login(self.params.username, self.params.password)
return { redirect_to = "/" }
end
}))
在一个函数里声明了三个闭包函数,before、GET、POST,其中的GET,POST函数就是用来响应不同的类型请求。