![](/img/trans.png)
[英]How do I redirect devise sign_in path to a different controller and view? Note:This is before the authentication happens
[英]How do I stop devise from trying to redirect to /users/sign_in for API requests?
在我的反應前端,我有一個 API 請求,該請求通過 axios 庫發送到我在 rails 后端的 ruby:
Axios({
url: "/terms",
headers: {
'Authorization': token
}
}).then((response) => {
console.log(response.request)
setActiveSet(response.data)
setActiveSetIndex(0)
}).catch((error) => {
console.log(error)
})
執行上述請求時,我在后端日志(ruby on rails)中看到以下響應鏈:
Started GET "/terms" for 192.168.1.119 at 2021-01-05 13:54:02 -0700
Cannot render console from 192.168.1.119! Allowed networks: 127.0.0.0/127.255.255.255, ::1
Processing by TermsController#index as HTML
Completed 401 Unauthorized in 0ms (ActiveRecord: 0.0ms | Allocations: 491)
Started GET "/users/sign_in" for 192.168.1.119 at 2021-01-05 13:54:02 -0700
Cannot render console from 192.168.1.119! Allowed networks: 127.0.0.0/127.255.255.255, ::1
Processing by Devise::SessionsController#new as JSON
Completed 200 OK in 1ms (Views: 0.2ms | ActiveRecord: 0.0ms | Allocations: 907)
Started GET "/terms" for 192.168.1.119 at 2021-01-05 13:54:02 -0700
Cannot render console from 192.168.1.119! Allowed networks: 127.0.0.0/127.255.255.255, ::1
Processing by TermsController#index as HTML
Completed 401 Unauthorized in 1ms (ActiveRecord: 0.0ms | Allocations: 491)
Started GET "/users/sign_in" for 192.168.1.119 at 2021-01-05 13:54:02 -0700
Cannot render console from 192.168.1.119! Allowed networks: 127.0.0.0/127.255.255.255, ::1
Processing by Devise::SessionsController#new as JSON
Completed 200 OK in 1ms (Views: 0.2ms | ActiveRecord: 0.0ms | Allocations: 905)
.catch
塊永遠不會被調用。 當我查看響應時,我看到 2 個成功的 200 個響應。 401 響應不會顯示在前端。
我正在嘗試捕獲 401 狀態代碼,然后通過我的反應前端向用戶顯示登錄表單。 后端(設計 gem)試圖將我重定向到 /users/sign_in,這不是我想要發生的。 我只想要一個 401,以便我的 react 應用程序可以顯示自己的登錄表單,但由於我不知道的原因,axios 僅顯示具有 200 個狀態的響應。
您可以通過更改失敗應用程序來修改身份驗證失敗時的響應:
module MyNamespace
class FailureApp < Devise::FailureApp
def respond
request.format.json? ? api_response : super
end
private
def api_response
self.status = 401
self.content_type = 'application/json'
# optional - send a message in the response body
# response.body = { error: i18n_message }.to_json
end
end
end
# add to config/initializers/devise.rb
config.warden do |manager|
manager.failure_app = MyNamespace::FailureApp
end
失敗應用程序只是一個基於ActionController::Metal構建的基本 Rack 應用程序,當 Warden 拋出時(當用戶身份驗證失敗時)被調用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.