# [laravel][laravel5.8][csrf][ajax]CSRF問題處理
###### tags: `laravel`,`laravel5.8`,`csrf`,`ajax`
參考資料:
https://stackoverflow.com/questions/32738763/laravel-csrf-token-mismatch-for-ajax-post-request
https://laravel.com/docs/5.8/csrf
在laravel中,一般的form提交只要加上@csrf即可:
```htmlmixed=
<form method="POST" action="/profile">
@csrf
...
</form>
```
關於ajax處理csrf的部份,[這個連結](https://stackoverflow.com/questions/32738763/laravel-csrf-token-mismatch-for-ajax-post-request)有很多的解決方式,
但[laravle官網](https://laravel.com/docs/5.8/csrf)有提到:
...
***CSRF Tokens & JavaScript***
When building JavaScript driven applications, it is convenient to have your JavaScript HTTP library automatically attach the CSRF token to every outgoing request. ***By default, the resources/js/bootstrap.js file registers the value of the csrf-token meta tag with the Axios HTTP library.*** If you are not using this library, you will need to manually configure this behavior for your application.
...
總之就是laravel預設已經有附加axios這個好用的library,而且csrf token也都註冊好了,若是使用axios去運行ajax,就不需再額外對csrf token做處理:
```htmlembedded!
axios({
method: 'POST',
url: "{{ route('todo.store') }}",
data: {
form_data: $('#form_create_todo').serializeArray()
}
})
.then(function(data){
console.log('success');
console.log(data);
})
.catch(function(data){
console.log('failed');
console.log(data);
})
```
要注意的是axios沒有fail function,
要改成catch進行錯誤處理,
這點跟jquery ajax不同.
附上jquery ajax的csrf處理方式:
```htmlmixed!
$.ajax({
url: "{{ route('todo.store') }}",
method:"POST",
data: {
//加上這一行
"_token": "{{ csrf_token() }}",
form_data: $('#form_create_todo').serializeArray()
}
})
.then(function(data){
console.log('success');
console.log(data);
})
.fail(function(data){
console.log('failed');
console.log(data);
})
```
>上述寫法必須script跟html在同一個檔案中.
>js跟html分開的csr ftoken解法請參考<b>[這個連結](https://stackoverflow.com/questions/32738763/laravel-csrf-token-mismatch-for-ajax-post-request)</b>
>