実現したいこと
https://qiita.com/masakiwakabayashi/items/58734b3988d5fac814fb
という記事を参考にコードを書いていてnext.js側からlaravel側に
http.post('/api/login'でログインの認証その際にsancutmの認証も行いたい
発生している問題・分からないこと
記載したコードの
http.post('/api/login', {email, password}).then((res: any) => {
console.log(res);
})
の部分でエラーが起きていそうです。
axios.get('http://localhost/sanctum/csrf-cookie', { withCredentials: true }).then((res: any) => {
console.log(res);
の実行したconsole.logは204で表示されていたので問題ないのかと思ってます。
エラーメッセージ
error
1{data: '', status: 204, statusText: 'No Content', headers: AxiosHeaders, config: {…}, …} 2config 3: 4{transitional: {…}, adapter: Array(2), transformRequest: Array(1), transformResponse: Array(1), timeout: 0, …} 5data 6: 7"" 8headers 9: 10AxiosHeaders {cache-control: 'no-cache, private'} 11request 12: 13XMLHttpRequest {onreadystatechange: null, readyState: 4, timeout: 0, withCredentials: true, upload: XMLHttpRequestUpload, …} 14status 15: 16204 17statusText 18: 19"No Content" 20[[Prototype]] 21: 22Object 23 24Uncaught (in promise) AxiosError {message: 'Request failed with status code 419', name: 'AxiosError', code: 'ERR_BAD_REQUEST', config: {…}, request: XMLHttpRequest, …} 25postData @ Test.tsx:28 26await in postData (async) 27onClick @ Test.tsx:54 28callCallback @ react-dom.development.js:20461 29invokeGuardedCallbackImpl @ react-dom.development.js:20510 30invokeGuardedCallback @ react-dom.development.js:20585 31invokeGuardedCallbackAndCatchFirstError @ react-dom.development.js:20599 32executeDispatch @ react-dom.development.js:31936 33processDispatchQueueItemsInOrder @ react-dom.development.js:31968 34processDispatchQueue @ react-dom.development.js:31981 35dispatchEventsForPlugins @ react-dom.development.js:31992 36eval @ react-dom.development.js:32182 37batchedUpdates$1 @ react-dom.development.js:24793 38batchedUpdates @ react-dom.development.js:28653 39dispatchEventForPluginEventSystem @ react-dom.development.js:32181 40dispatchEvent @ react-dom.development.js:29949 41dispatchDiscreteEvent @ react-dom.development.js:29920 42Show 14 more frames 43Show less 44Test.tsx:22 45 46 47 POST http://localhost/api/login 419 (unknown status) 48dispatchXhrRequest @ xhr.js:272 49xhr @ xhr.js:63 50dispatchRequest @ dispatchRequest.js:61 51request @ Axios.js:155 52httpMethod @ Axios.js:194 53wrap @ bind.js:9 54postData @ Test.tsx:22 55await in postData (async) 56onClick @ Test.tsx:54 57callCallback @ react-dom.development.js:20461 58invokeGuardedCallbackImpl @ react-dom.development.js:20510 59invokeGuardedCallback @ react-dom.development.js:20585 60invokeGuardedCallbackAndCatchFirstError @ react-dom.development.js:20599 61executeDispatch @ react-dom.development.js:31936 62processDispatchQueueItemsInOrder @ react-dom.development.js:31968 63processDispatchQueue @ react-dom.development.js:31981 64dispatchEventsForPlugins @ react-dom.development.js:31992 65eval @ react-dom.development.js:32182 66batchedUpdates$1 @ react-dom.development.js:24793 67batchedUpdates @ react-dom.development.js:28653 68dispatchEventForPluginEventSystem @ react-dom.development.js:32181 69dispatchEvent @ react-dom.development.js:29949 70dispatchDiscreteEvent @ react-dom.development.js:29920 71Show 20 more frames 72Show less 73settle.js:24 Uncaught (in promise) AxiosError {message: 'Request failed with status code 419', name: 'AxiosError', code: 'ERR_BAD_REQUEST', config: {…}, request: XMLHttpRequest, …}
該当のソースコード
"use client"; import React, { useEffect, useState } from 'react'; import axios from 'axios'; // XSRF-TOKENをリクエスト時に送信するための設定 const http = axios.create({ baseURL: 'http://localhost', withCredentials: true, }); const Test = () => { const [email, setEmail] = useState(''); const [password, setPassword] = useState(''); const postData = async () => { axios.get('http://localhost/sanctum/csrf-cookie', { withCredentials: true }).then((res: any) => { console.log(res); // ログイン処理 http.post('/api/login', {email, password}).then((res: any) => { console.log(res); }) }); } return ( <div> <input type="text" className='bg-gray-200 appearance-none border-2 border-gray-200 rounded w-full py-2 px-4 text-gray-700 leading-tight focus:outline-none focus:bg-white focus:border-purple-500 m-3 max-w-sm' placeholder='email' onChange={(e) => { setEmail(e.target.value); }} /><br/> <input type="text" className='bg-gray-200 appearance-none border-2 border-gray-200 rounded w-full py-2 px-4 text-gray-700 leading-tight focus:outline-none focus:bg-white focus:border-purple-500 m-3 max-w-sm' placeholder='password' onChange={(e) => { setPassword(e.target.value); }} /> <div> <button className="shadow bg-purple-500 hover:bg-purple-400 focus:shadow-outline focus:outline-none text-white font-bold py-2 px-4 rounded m-3" onClick={()=>{ postData(); }} >送信</button> </div> </div> ); } export default Test;
試したこと・調べたこと
- teratailやGoogle等で検索した
- ソースコードを自分なりに変更した
- 知人に聞いた
- その他
上記の詳細・結果
Kernel.phpに
\App\Http\Middleware\VerifyCsrfToken::class,
と
\Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
が記載されていることを確認
sanctum.phpには下記を記載されていることを確認
'stateful' => explode(',', env('SANCTUM_STATEFUL_DOMAINS', sprintf(
'%s%s',
'localhost:8080,localhost:3000,127.0.0.1,127.0.0.1:8000,::1',//本番環境に合わせてドメイン変更必要
Sanctum::currentApplicationUrlWithPort()
.envには下記を記載
#sanctum
SESSION_DRIVER=cookie
SESSION_DOMAIN=localhost:8080
SANCTUM_STATEFUL_DOMAINS=localhost:3000
こちらのサイトの方のgithubを見ながらファイルも確認しました。
補足
kernel.phpや
next.js側にwithCredentials: true }があることも確認して実行しましたが419のエラーが発生しました。
有識者の方で解決方法をご存知の方いらっしゃいましたら助言いただきたいです。
よろしくお願いいたします。
バージョンは
Laravel Framework 10.38.2
yarn list v1.22.19
になります

回答1件
あなたの回答
tips
プレビュー