Http Post in laravel using fetch api giving TokenMismatchException
function post(id){
const token = '{{ csrf_token() }}';
web = "{{request()->getHttpHost()}}" ;
url = 'http://' + web + '/metodo';
fetch(url, {
method: 'post',
credentials: "same-origin",
headers: {
'Content-Type': 'application/json',
"X-CSRF-Token": token
},
body: JSON.stringify({
key: id
})
}).then(response => {
return response.json();
}).then(text => {
return console.log(text);
}).catch(error => console.error(error));
}
I may be late to the party but this works too
fetch("/audio/signed", {
headers: {
"Content-Type": "application/json",
"Accept": "application/json",
"X-Requested-With": "XMLHttpRequest",
"X-CSRF-Token": $('input[name="_token"]').val()
},
method: "post",
credentials: "same-origin",
body: JSON.stringify({
key: "value"
})
})
index.blade.php
<meta name="csrf-token" content="{{ csrf_token() }}">
app.js
const csrfToken = document.head.querySelector("[name~=csrf-token][content]").content;
function orderPost(order) {
fetch('/orders', {
method: 'post',
body: JSON.stringify(order),
headers: {
'Content-Type': 'application/json',
"X-CSRF-Token": csrfToken
}
})
.then(response => {
return response.text();
})
.then(text => {
return console.log(text);
})
.catch(error => console.error(error));
};
OrderController.php
public function store(Request $request){
$order = new Order();
$order->user_id = $request->json('user_id');
$order->item_list = $request->json('item_list');
$order->leave_note = $request->json('leave_note');
$order->total = $request->json('total');
$order->save();
$response = [
'status' => 'success',
'message' => 'order stored',
];
return response()->json($response);
}
I was able to make it work.
There were 2 changes I have to make
1) Fetch Api don't use cookie by default. So to make it use cookie I added
credentials: "same-origin"
2)the data need to be submitted in Form data format rather than json
so here's my working code
var URL = $("#form").attr("action");
var token = $("input[name='_token']").val();
var group_id = $(this).val();
fetch(URL, {
method: 'post',
credentials: "same-origin",
body: new FormData(document.getElementById('form'))
}).then(function(response){
return response.json();
}) .then(function(json){
// change course
})
.catch(function(error){
});