【问题标题】:POST request to users/sign_in is returning HTML and no response?对 users/sign_in 的 POST 请求返回 HTML 并且没有响应?
【发布时间】:2021-07-31 16:33:39
【问题描述】:

我正在尝试设计与我的 React 前端一起使用。目前我已经在前端设置了一个 AuthenticationService 来让用户登录。这是我第一次使用 React 设置设计,所以我确定我遗漏了一些东西,但我似乎无法弄清楚什么。

图片显示的是我在控制台记录来自 API 的响应时得到的。

这是我的身份验证服务在前端的样子。

class AuthenticationService {
  async signIn(values) {
    return axios
      .get(`/users/sign_in`, { user: values })
      .then((response) => response.data)
  }
}

export default new AuthenticationService()

我有一个空的 Users::SessionsController,我的前端看起来像下面的代码。我正在使用 Formik 提交表单,提交表单时的值是正确的,我目前只是 console.logging 响应以了解从 AuthenticationService 传回的数据。

<Formik
  initialValues={{ email: "", password: "" }}
  onSubmit={async (values) => {
    console.log("values", values)
    try {
      const response = await AuthenticationService.signIn(values)
      console.log("success?", response.success)
      if (response.success) {
        window.location.href = response.redirect
          ? console.log("response redirect")
          : console.log("/admin")
      }
    } catch {
      console.log("didn't work")
    }
  }}
>

这就是我的路线的样子

Rails.application.routes.draw do
  devise_for :users

  # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
  root to: "api/dashboard#home"

  namespace :api, defaults: { format: :json } do
    resources :dashboards
    resources :cookbooks
    resources :ingredients
    resources :recipes
  end
end

【问题讨论】:

    标签: ruby-on-rails reactjs authentication devise


    【解决方案1】:

    Devise 不支持 API 模式。 https://github.com/heartcombo/devise/issues/4997

    您可能想试试devise_token_auth gem。

    或者编写您的自定义控制器以正确处理 API 请求。 提示:如果您使用super,您最终会以html 模板响应或重定向到登录页面。所以不要使用它们。 https://github.com/heartcombo/devise/wiki/Tool:-Generate-and-customize-controllers

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-27
      • 2021-07-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多