前提
Nuxt.jsとRailsでサービスを作っています。現在ログイン機能を作成していますが、nuxt側のconfig
でauthの設定がうまくいきません。具体的にはuser欄のデータ取得ができません。原因と解決方法を教えていただきたいです。userをfalseにするとログイン情報が取得できるので、恐らくrails側に問題があると思います・・
実現したいこと
・nuxrt/authのログイン情報を取得したい。
発生している問題・エラーメッセージ
js
1{data: {…}, status: 401, statusText: 'Unauthorized', headers: {…}, config: {…}, …} 2config: {url: '/api/v1/auth/sessions', method: 'get', headers: {…}, baseURL: 'http://localhost:3000', transformRequest: Array(1), …} 3data: 4errors: ['アカウント登録もしくはログインしてください。']
該当のソースコード
Nuxt
config
js
1 modules: [ 2 // https://go.nuxtjs.dev/axios 3 '@nuxtjs/axios', 4 '@nuxtjs/auth' 5 ], 6 7 // Axios module configuration: https://go.nuxtjs.dev/config-axios 8 axios: { 9 baseURL: 'http://localhost:3000' 10 }, 11 12 auth: { 13 redirect: { 14 login: '/user/login', 15 logout: '/user/login', 16 callback: false, 17 home: '/' 18 }, 19 strategies: { 20 local: { 21 endpoints: { 22 login: { url: '/api/v1/auth/sign_in', method: 'post', propertyName: 'token' }, 23 logout: { url: '/api/v1/auth/sign_out', method: 'delete' }, 24 // user: false 25 user: { url: '/api/v1/auth/sessions', method: 'get', propertyName: false } 26 } 27 } 28 } 29 }, 30 // Build Configuration: https://go.nuxtjs.dev/config-build 31 build: { 32 }, 33 34 router: { 35 middleware: ['auth'] 36 } 37}
components
js
1<script> 2import logoImg from '~/assets/images/login_logo.png' 3export default { 4 auth: false, 5 data () { 6 return { 7 logoImg, 8 userInfo: { 9 email: '', 10 password: '' 11 } 12 } 13 }, 14 15 methods: { 16 async login () { 17 await this.$auth.loginWith('local', { 18 data: { 19 email: this.userInfo.email, 20 password: this.userInfo.password 21 } 22 }) 23 .then( 24 (response) => { 25 // レスポンスで返ってきた、認証に必要な情報をlocalStorageに保存 26 localStorage.setItem('access-token', response.headers['access-token']) 27 localStorage.setItem('client', response.headers.client) 28 localStorage.setItem('uid', response.headers.uid) 29 localStorage.setItem('token-type', response.headers['token-type']) 30 return response 31 }, 32 (error) => { 33 return error 34 } 35 ) 36 } 37 } 38} 39</script>
Rails
SessionsController
rb
1class Api::V1::Auth::SessionsController < ApplicationController 2 before_action :authenticate_api_v1_user! 3 def index 4 render json: 'ログイン成功' 5 end 6end 7
RegistrationsController
rb
1class Api::V1::Auth::RegistrationsController < DeviseTokenAuth::RegistrationsController 2 3 private 4 def sign_up_params 5 params.permit(:name, :email, :password, :password_confirmation) 6 end 7end 8
routes
rb
1Rails.application.routes.draw do 2 namespace :api do 3 namespace :v1 do 4・ 5・ 6・ 7 mount_devise_token_auth_for 'User', at: 'auth', controllers: { 8 registrations: 'api/v1/auth/registrations' 9 } 10 11 namespace :auth do 12 resources :sessions, only: [:index] 13 end 14・ 15・ 16・ 17 end 18 end 19end 20
試したこと
・Railsのコントローラーをauthenticate_user!
からauthenticate_api_v1_user!
に変更
・RegistrationsController
にindex
アクションを追加してみようとしたが。deviseにないアクションだったのでエラーになった
あなたの回答
tips
プレビュー