I am trying to make a http post using fetch api. Even though I am sending the token, I am getting error TokenMismatchException in VerifyCsrfToken.php . How can I make the call using fetch api? (I also tried with jQuery ajax and its working perfectly) Heres the fetch api code
var URL = $("#form").attr("action");
var token = $("input[name='_token']").val();
var group_id = $(this).val();
fetch(URL, {
method: 'post',
mode: 'no-cors',
body: JSON.stringify({
'csrf-token': token,
'group_id': group_id
})
}).then(function(response){
return response.json();
}) .then(function(json){
})
.catch(function(error){
});
I have added token in form like this
<form id="form" action="{{ url('api/getcoursebygroup') }}">
<input type="hidden" name="_token" id="csrf-token" value="{{ Session::token() }}" />
</form>
This jQuery ajax call is working fine :
$.ajax({
type: "POST",
url: URL,
data: { "group_id" : group_id, "_token" : token },
dataType: 'json'
}).done(function (result) {
if(result.code == 1){
}
});
jQuery ajax call headers
Fetch api call headers
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"
})
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With