php Laravel 5.5 ajax 调用 419(状态未知)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46466167/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel 5.5 ajax call 419 (unknown status)
提问by Chris
I do an ajax call but I keep getting this error:
我做了一个ajax调用,但我一直收到这个错误:
419 (unknown status)
419(未知状态)
No idea what is causing this I saw on other posts it has to do something with csrf token but I have no form so I dont know how to fix this.
不知道是什么导致了这个我在其他帖子上看到它必须用 csrf 令牌做一些事情但我没有表格所以我不知道如何解决这个问题。
my call:
我的电话:
$('.company-selector li > a').click(function(e) {
e.preventDefault();
var companyId = $(this).data("company-id");
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
url: '/fetch-company/' + companyId,
dataType : 'json',
type: 'POST',
data: {},
contentType: false,
processData: false,
success:function(response) {
console.log(response);
}
});
});
My route:
我的路线:
Route::post('fetch-company/{companyId}', 'HomeController@fetchCompany');
My controller method
我的控制器方法
/**
* Fetches a company
*
* @param $companyId
*
* @return array
*/
public function fetchCompany($companyId)
{
$company = Company::where('id', $companyId)->first();
return response()->json($company);
}
The ultimate goal is to display something from the response in a html element.
最终目标是在 html 元素中显示响应中的某些内容。
回答by Kannan K
Use this in the head section:
在 head 部分使用它:
<meta name="csrf-token" content="{{ csrf_token() }}">
and get the csrf token in ajax:
并在ajax中获取csrf令牌:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
Please refer Laravel Documentation csrf_token
请参考 Laravel 文档csrf_token
回答by Waqas Bukhary
Another way to resolve this is to use the _token
field in ajax data and set the value of {{csrf_token()}}
in blade. Here is a working code that I just tried at my end.
解决此问题的另一种方法是使用_token
ajax 数据中的字段并设置{{csrf_token()}}
刀片中的值。这是我刚刚尝试过的工作代码。
$.ajax({
type: "POST",
url: '/your_url',
data: { somefield: "Some field value", _token: '{{csrf_token()}}' },
success: function (data) {
console.log(data);
},
error: function (data, textStatus, errorThrown) {
console.log(data);
},
});
回答by Damien ó Ceallaigh
This is similar to Kannan's answer. However, this fixes an issue where the token should not be sent to cross-domain sites. This will only set the header if it is a local request.
这类似于 Kannan 的回答。但是,这解决了不应将令牌发送到跨域站点的问题。如果它是本地请求,这只会设置标头。
HTML:
HTML:
<meta name="csrf-token" content="{{ csrf_token() }}">
JS:
JS:
$.ajaxSetup({
beforeSend: function(xhr, type) {
if (!type.crossDomain) {
xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'));
}
},
});
回答by Y. Joy Ch. Singha
use this in your page
在您的页面中使用它
<meta name="csrf-token" content="{{ csrf_token() }}">
and in your ajax used it in data:
并在您的 ajax 数据中使用它:
_token: '{!! csrf_token() !!}',
that is:
那是:
$.ajax({
url: '/fetch-company/' + companyId,
dataType : 'json',
type: 'POST',
data: {
_token: '{!! csrf_token() !!}',
},
contentType: false,
processData: false,
success:function(response) {
console.log(response);
}
});
Thanks.
谢谢。
回答by Jeff Callahan
It's possible your session domain does not match your app URL and/or the host being used to access the application.
您的会话域可能与您的应用程序 URL 和/或用于访问应用程序的主机不匹配。
1.) Check your .env file:
1.) 检查您的 .env 文件:
SESSION_DOMAIN=example.com
APP_URL=example.com
2.) Check config/session.php
2.) 检查 config/session.php
Verify values to make sure they are correct.
验证值以确保它们正确。
回答by 2Fwebd
If you already done the above suggestions and still having the issue.
如果您已经完成了上述建议,但问题仍然存在。
Make sure that the env variable:
确保 env 变量:
SESSION_SECURE_COOKIE
Is set to false
ifyou don't have a SSL certificate, like on local.
false
如果您没有 SSL 证书,则设置为,例如在本地。
回答by The Dead Guy
in my case i forgot to add csrf_token input to the submitted form. so i did this HTML:
就我而言,我忘记将 csrf_token 输入添加到提交的表单中。所以我做了这个 HTML:
<form class="form-material" id="myform">
...
<input type="file" name="l_img" id="l_img">
<input type="hidden" id="_token" value="{{ csrf_token() }}">
..
</form>
JS:
JS:
//setting containers
var _token = $('input#_token').val();
var l_img = $('input#l_img').val();
var formData = new FormData();
formData.append("_token", _token);
formData.append("l_img", $('#l_img')[0].files[0]);
if(!l_img) {
//do error if no image uploaded
return false;
}
else
{
$.ajax({
type: "POST",
url: "/my_url",
contentType: false,
processData: false,
dataType: "json",
data : formData,
beforeSend: function()
{
//do before send
},
success: function(data)
{
//do success
},
error: function(jqXhr, textStatus, errorThrown) //jqXHR, textStatus, errorThrown
{
if( jqXhr.status === "422" ) {
//do error
} else {
//do error
}
}
});
}
return false; //not to post the form physically
回答by Tharanga
Even though you have a csrf_token
, if you are authenticate your controller actions using Laravel Policies
you can have 419 response as well. In that case you should add necessary policy functions in your Policy
class.
即使您有一个csrf_token
,如果您使用 Laravel 验证您的控制器操作,Policies
您也可以获得 419 响应。在这种情况下,您应该在Policy
类中添加必要的策略函数。
回答by Wolfernand
If you are loading .js from a file you have to set a variable with the csrf_token in your "main" .blade.php file where you are importing the .js and use the variable in your ajax call.
如果您从文件加载 .js,则必须在“主”.blade.php 文件中使用 csrf_token 设置一个变量,您将在其中导入 .js 并在 ajax 调用中使用该变量。
index.blade.php
index.blade.php
...
...
<script src="{{ asset('js/anotherfile.js') }}"></script>
<script type="text/javascript">
var token = '{{ csrf_token() }}';
</script>
anotherfile.js
另一个文件.js
$.ajax({
url: 'yourUrl',
type: 'POST',
data: {
'_token': token
},
dataType: "json",
beforeSend:function(){
//do stuff
},
success: function(data) {
//do stuff
},
error: function(data) {
//do stuff
},
complete: function(){
//do stuff
}
});
回答by Muhammad Umair
just serialize the form data and get your problem solved.
只需序列化表单数据即可解决您的问题。
data: $('#form_id').serialize(),