在laravel中的Http Post使用fetch api给出TokenMismatchException
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
我正在尝试使用fetch api制作一篇http帖子。即使我发送令牌,我在VerifyCsrfToken.php中收到错误TokenMismatchException。如何使用fetch api拨打电话? (我也尝试过使用jQuery ajax并且它的工作正常)继承人fetch api代码
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 :
这个jQuery ajax调用工作正常:
$.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
jQuery ajax调用头文件
Fetch api call headers
获取api调用头
4 个解决方案
#1
9
Finally 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
1)Fetch Api默认情况下不使用cookie。所以要使用我添加的cookie
credentials: "same-origin"
凭证:“同源”
2)the data need to be submitted in Form data format rather than json
2)数据需要以表格数据格式而不是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){
});
更多相关文章
- 循环不能正常工作 - 守夜人
- 无法让.click()在禁用的textarea上工作
- Vue js v-bind不工作?
- JQuery 1.4.4和Datatable 1.7不工作
- 单击它时,为什么下拉菜单不在我的导航栏中工作?
- 为什么jquery click事件在plunker中工作但在任何浏览器中都没有
- AngularJS身份验证和基于XSRF令牌
- setInterval在Chrome上不能正常工作
- 单选按钮单击,隐藏/显示不工作