Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
127
rated 0 times [  130] [ 3]  / answers: 1 / hits: 31049  / 8 Years ago, tue, july 5, 2016, 12:00:00

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



enter



Fetch api call headers



enter


More From » jquery

 Answers
6

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){


});

[#61509] Sunday, July 3, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
turnerf

Total Points: 620
Total Questions: 101
Total Answers: 109

Location: French Polynesia
Member since Tue, Jul 7, 2020
4 Years ago
turnerf questions
;