問題描述:
在使用 laravel 框架進行 ajax 提交的時候,一直報錯 419,想了下肯定是 csrf_token 問題。仔細看了下官方文件:
javascript 的 header 頭和 meta 標籤都已經新增了,一直找不到問題出在哪裡。
<meta name="csrf-token" content="{{ csrf_token() }}">
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
於是試用了正常情況下的表單提交,也是認證不通過。但這個時候有了個明確的錯誤資訊提示:
The page has expired due to inactivity. Please refresh and try again.
在網上找了下,馬上就找到了解決方案:
May have something to do with the storage_path not being writable. This is where it stores session data regarding tokens if you're using file based sessions.
As stated in the comments, the session driver was set to array. Array is for testing only. Since data is not persisted, it will not be able to compare the token on the next request.
The array driver is used during testing and prevents the data stored in the session from being persisted.
總結:
- 多看看官方文件。
- 儘量使用「官方推薦的開發環境」。
附言:
以前我也一直用 homestead 進行開發,由於每次都要啟動,電腦配置又有點差,加上用的 ubuntu OS。
所以覺得沒必要再用 homestead,但是下來走了一些坑。就比如這個問題,花了我快一個小時的時間。