我安装了Laravel 5.7
在文件中添加了一个表单 \resources\views\welcome.blade.php
<form method="POST" action="/foo" >
@csrf
<input type="text" name="name"/><br/>
<input type="submit" value="Add"/>
</form>
Run Code Online (Sandbox Code Playgroud)
添加到文件 \routes\web.php
Route::post('/foo', function () {
echo 1;
return;
});
Run Code Online (Sandbox Code Playgroud)
发送POST请求后:
419抱歉,您的会话已过期.请刷新并重试.
在版本5.6中没有这样的问题.
我正在开发一个Laravel 5应用程序,该应用程序默认为所有POST请求启用CSRF保护.我喜欢这个增加的安全性所以我正在尝试使用它.
在发出简单$.post()请求时,我收到'Illuminate\Session\TokenMismatchException'错误,因为_tokenPOST数据中缺少所需的表单输入.以下是有问题的$ .post请求的示例:
var userID = $("#userID").val();
$.post('/admin/users/delete-user', {id:userID}, function() {
// User deleted
});
Run Code Online (Sandbox Code Playgroud)
我将CSRF令牌存储为标题中的元字段,可以使用以下方法轻松访问它:
var csrf_token = $('meta[name="csrf-token"]').attr('content');
Run Code Online (Sandbox Code Playgroud)
是否可以将此附加到所有传出$.post()请求的json数据?我尝试使用标题,但Laravel似乎没有认出它们 -
var csrf_token = $('meta[name="csrf-token"]').attr('content');
alert(csrf_token);
$.ajaxPrefilter(function(options, originalOptions, jqXHR){
if (options['type'].toLowerCase() === "post") {
jqXHR.setRequestHeader('X-CSRFToken', csrf_token);
}
});
Run Code Online (Sandbox Code Playgroud) 我有这种形式,用户只应在文本区域内键入文本:
<form action="#" v-on:submit="postStatus">{{-- Name of the method in Vue.js --}}
<div class="form-group">
<textarea class="form-control" rows="5" maxlength="140" autofocus placeholder="What are you upto?" required v-model="post"></textarea>
</div>
<input type="submit" value="Post" class="form-control btn btn-info">
{{ csrf_field() }}
</form>
Run Code Online (Sandbox Code Playgroud)
然后,我有这个脚本代码,我将vue.js与ajax一起使用,以便将该文本传递给控制器并最终将其保存到数据库中:
//when we actually submit the form, we want to catch the action
new Vue({
el : '#timeline',
data : {
post : '',
},
http : {
headers: {
'X-CSRF-Token': $('meta[name=_token]').attr('content')
}
},
methods : {
postStatus : function (e) {
e.preventDefault();
console.log('Posted: '+this.post+ …Run Code Online (Sandbox Code Playgroud)