作者:蓝月亮乐悠悠 | 来源:互联网 | 2023-01-29 19:45
在phoenix framework
管道中,我们可以为某些路由启用指定中间件,例如:
defmodule HelloPhoenix.Router do
use HelloPhoenix.Web, :router
pipeline :browser do
plug :accepts, ["html"]
plug :fetch_session
plug :fetch_flash
plug :protect_from_forgery
plug :put_secure_browser_headers
end
pipeline :api do
plug :accepts, ["json"]
end
scope "/", HelloPhoenix do
pipe_through :browser # Use the default browser stack
get "/", PageController, :index
end
scope "/api", HelloPhoenix do
pipe_through :api
end
end
如果请求来自/api
,只会触发plug :accepts, ["json"]
中间件
如果请求来自/
,将触发会话,闪存,...等中间件
如何在rails上实现这一点,如果我使用grape
构建api和rails来构建网页并为彼此启用差异中间件?
1> Ryan Bigg..:
与Phoenix应用程序不同,您无法(轻松)更改Rails中用于请求的中间件.在Rails应用程序中获得此类行为的最佳方法是使特定路由的控制器继承自公共基本控制器,然后在该基本控制器中定义这些特定控制器的行为.
使用上面/api
通过不同"中间件" 的路由示例,您可以拥有这样的控制器:
module API
class BaseController
在这个控制器里面,你可以写一些before_action
回调来确保这样的事情:
入站请求仅限JSON
请求使用特定令牌进行身份验证
然后,您可以从此控制器继承所有API控制器:
module API
class PostsController
使用常规控制器,您可以执行所有常规操作:
class ApplicationController
然后:
class PostsController
你当然可以将它分割得更多; 也许你可能有另一条路线,比如/accounts/1/posts
你必须要作为该帐户的用户进行身份验证才能查看帖子.您可以采用相同的方法:
module Accounts
class BaseController
和:
module Accounts
class PostsController
总而言之:Rails不允许您在路由级别(轻松)执行此操作,但您可以在控制器级别完成相同的操作.