LoginSignup
2
0

More than 1 year has passed since last update.

【React】device_token_authのcurrent_userでユーザーデータが返ってこないときの対処法【axios】

Posted at

症状

ReactとRailsAPIでアプリを作成し、Railsにdevice_token_authの導入したところ、サインアップ、サインイン、サインアウトは成功するものの、サインインしている状態で、device_token_authのcurrent_userメソッドではnilやuser_signed_inではfalseが返ってきてしまう症状に遭遇しました。

エラー
#サインインしている状態なのに、下記になる
current_user #nil

user_signed_in #false

結論から言うと、current_userをaxiosでアクセスする際に、access-token,uid,clientの情報が必要で、それを送っていなかったためにcurrent_userでnilが返ってくる状態になっていました。

フロント側はユーザー情報を持っていたとしても、サーバー側に送られていなければ、サーバーは「このリクエストはどのユーザーから送られたものなの?」となってしまうようです。

では、サーバー側に必要なデータを送る実装方法について書いていきます。

解決方法(実装)

実装はいたってシンプル。
axiosでデータを送る際に、下記のように必要な情報をjsonで渡してあげればサーバー側も認証情報を受け取ることができます。

以下ではログイン情報を確認するもので、Cookiesに保存していたaccess-token,uid,clientの情報を取得し、axiosでRails側に送信します。

axios
import axios from "axios";
import React from "react";
import Cookies from "js-cookie";

//ログイン状態をチェックする
export const isLoginApi = () => {
    const uid = Cookies.get("uid");
    const accessToken = Cookies.get("access_token");
    const client = Cookies.get("client");
    return axios.get(sessionIsLogin,{
        headers: {
          'access-token': accessToken,
          client: client,
          uid: uid
        },
      })
    .then(res => {
        return res.data
    })
    .catch((e) => console.error(e))
}

参考

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0