问题描述
我已经将 Rails 6 后端与 Devise 和 Devise 令牌身份验证以及使用 API 的前端 Angular Nativescript 应用程序组合在一起。参考;
后端:https://github.com/map7/backend_rails6_template
移动前端:https://github.com/map7/frontend_nativescript
我的问题是,如果我不需要版本控制,我是否必须为 API 和网页复制我的控制器?
Devise_token_auth 建议我需要命名空间,如果我要与 Devise 一起使用它。
class HomeController < ApplicationController
before_action :authenticate_user!
end
哪个使用这个 ApplicationController
class ApplicationController < ActionController::Base
protect_from_forgery unless: -> { request.format.json? }
end
对于 API 调用,我在 api/v1/home_controller 中有另一个 Home Controller,如下所示;
module Api
module V1
class HomeController < ApplicationController
before_action :authenticate_user!
def index
render json: {message: "Welcome to the Ruby on Rails backend"}
end
end
end
end
哪个使用这个 ApplicationController
module Api
module V1
class ApplicationController < ActionController::API
include DevisetokenAuth::Concerns::SetUserByToken
before_action :authenticate_user!
before_action :configure_permitted_parameters,if: :devise_controller?
protected
def configure_permitted_parameters
devise_parameter_sanitizer.permit(:sign_in,keys: [:email,:password])
end
end
end
end
我的 routes.rb 文件看起来像;
Rails.application.routes.draw do
devise_for :users # Standard devise routes must come first!
resources :home,only: [:index]
root to: "home#index"
namespace :api,defaults: {format: 'json'} do # namespace devise token routes to stop duplication
namespace :v1 do
mount_devise_token_auth_for 'User',at: 'auth'
resources :home,only: [:index]
end
end
end
现在看起来可能没有太多重复,但我正在尝试转换一个大型应用程序,其中会有大量重复。如果我尝试为 API 调用调用 /home 路由,则会收到“未经授权的错误”。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)