お気に入り登録すると、ログインしているのにFilter chain halted as :authenticate_user!エラーが出る
解決したいこと
お気に入り機能が正常に動作するようにしたい
Rails-api+Next.js+Typescriptでお気に入り機能の実装を試みています。
認証機能はdevise,devise_token_authを使用しています。
お気に入り登録ボタンを押すとログイン状態なのにユーザーが認証されていないためフィルターによってアクセスが制限されたという内容の以下のエラーが出ます。ログインした時は200が返ってきています。
・エラー文
Processing by FavoritesController#create as HTML
Parameters: {"book_id"=>"3", "favorite"=>{}}
Filter chain halted as :authenticate_user! rendered or redirected
Completed 401 Unauthorized in 189ms (Views: 30.4ms | ActiveRecord: 0.0ms | Allocations: 139)
コントローラー
favorites_controller.rb
class FavoritesController < ApplicationController
before_action :authenticate_user!
def create
book = Book.find(params[:book_id])
favorite = current_user.favorites.new(book_id: book.id)
if favorite.save
render json: { message: "Favorite created successfully" }, status: :created
else
render json: { errors: favorite.errors.full_messages }, status: :unprocessable_entity
end
end
def destroy
book = Book.find(params[:book_id])
favorite = current_user.favorites.find_by(book_id: book.id)
if favorite
favorite.destroy
render json: { message: "Favorite deleted successfully" }, status: :no_content
else
render json: { message: "Favorite not found" }, status: :not_found
end
end
end
リクエスト部分を含むフロントエンドのコード
pages / index.tsx
import React, { useState } from "react";
import { useRouter } from "next/router";
import axios from "axios";
import Cookies from "js-cookie";
const Login = () => {
const router = useRouter();
const [isError, setIsError] = useState(false);
const [errorMessage, setErrorMessage] = useState("");
const handleSubmit = async (event) => {
event.preventDefault();
const formData = new FormData(event.currentTarget);
try {
const response = await axios.post("http://localhost:3000/api/v1/auth/sign_in", {
email: formData.get("email"),
password: formData.get("password"),
});
// Cookieにトークンをセット
Cookies.set("uid", response.headers["uid"]);
Cookies.set("client", response.headers["client"]);
Cookies.set("access-token", response.headers["access-token"]);
router.push("/home");
} catch (error) {
// Cookieからトークンを削除
Cookies.remove("uid");
Cookies.remove("client");
Cookies.remove("access-token");
setIsError(true);
setErrorMessage(error.response?.data?.errors[0] || "ログインエラーが発生しました");
}
};
return (
<div>
<h1>ログイン</h1>
<form onSubmit={handleSubmit}>
<div>
<label htmlFor="email">メールアドレス</label>
<input
type="email"
id="email"
name="email"
autoComplete="email"
autoFocus
/>
</div>
<div>
<label htmlFor="password">パスワード</label>
<input
type="password"
id="password"
name="password"
autoComplete="current-password"
/>
</div>
<button type="submit">ログイン</button>
</form>
{isError && (
<div className="error-message">
{errorMessage}
</div>
)}
<style jsx>{`
div {
max-width: 400px;
margin: 0 auto;
padding: 20px;
border: 1px solid #ccc;
border-radius: 4px;
}
h1 {
text-align: center;
}
label {
display: block;
margin-bottom: 6px;
}
input {
width: 100%;
padding: 8px;
margin-bottom: 12px;
border: 1px solid #ccc;
border-radius: 4px;
}
button {
display: block;
width: 100%;
padding: 10px;
background-color: #007bff;
color: #fff;
border: none;
border-radius: 4px;
cursor: pointer;
}
.error-message {
color: red;
text-align: center;
margin-top: 10px;
}
`}</style>
</div>
);
};
解決策を教えていただけますと幸いです。
0