url = '{{route("ajaxSendmsg")}}';
console.log(url);
$.ajax({
url: url,
data : {comment_id:comment_id},
type: "POST",
dataType: "json",
success : function(response){
alert(response);
},
error : function(res){
console.log(res);
}
});
路线:
Route::post('/ajaxSend', ['as'=> 'ajaxSendmsg', 'uses'=>'PostsController@ajaxSend']);
控制器:
public function ajaxSend(){
if( Request::ajax() ){
return Response::json(['success' => 1]);
}
}
错误:VerifyCsrfToken.php 53行中的TokenMismatchException:
我正在尝试发送ajax请求,但是它不起作用。 :/
参考方案
Laravel默认情况下在非读取HTTP请求(例如POST,PUT或PATCH)上具有中间件,以防止Cross Site Request Forgery。在每个响应上,都会生成一个令牌,然后预期随后的请求将与该令牌一起发送。如果令牌匹配,则一切正常,如果不匹配(或者请求完全不提供令牌),则可能是CSRF攻击。
有几种解决方法:
通过在app/Http/Kernel.php
中将其注释掉来完全禁用中间件-显然不是最好的主意。
通过使用自己的默认中间件覆盖默认的中间件,仅在确定不需要它的路由上禁用它:
``
<?php namespace App\Http\Middleware;
use Closure;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as BaseVerifier;
use Illuminate\Support\Str;
class VerifyCsrfToken extends BaseVerifier
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
*
* @return mixed
*/
public function handle($request, Closure $next)
{
if (Str::startsWith($request->getRequestUri(), 'some/open/route') {
return $next($request);
}
return parent::handle($request, $next);
}
}
只需在每个请求中将其发送,要么在请求正文中以_token
的形式发送,要么在请求字符串中以_token
的形式发送,或者以HTTP头名为X-CSRF-TOKEN
的形式发送。您可以使用辅助函数csrf_token()
来获得它:
``
.ajax({
url: url,
data : {comment_id:comment_id, "_token":"{{ csrf_token() }}"},
type: "POST",
dataType: "json",
....
});
在laravel 5中的静态函数中调用非静态函数 - php我正在使用laravel5。在模型中,我有一个静态函数,该函数在控制器中调用。它工作正常,但是我想在此函数中使用另一个非静态函数进行相同的更改,当我在静态函数中调用它时会产生错误。Non-static method App\Models\Course::_check_existing_course() should not be called statica…
PHP:将数组值加在一起 - php我相信这比标题听起来要难一些,但我可能完全错了。我有一个像这样的数组:[["londrina",15],["cascavel",34],["londrina",23],['tiradentes',34],['tiradentes',21]] 我希望能够采用通用…
PHP JQuery复选框 - php我有以下片段。 var myData = { video: $("input[name='video[]']:checked").serialize(), sinopse: $("#sinopse").val(), dia: $("#dia").val(), quem: $(…
PHP strtotime困境 - php有人可以解释为什么这在我的服务器上输出为true吗?date_default_timezone_set('Europe/Bucharest'); var_dump( strtotime('29.03.2015 03:00', time()) === strtotime('29.03.2015 04:00…
PHP-全局变量的性能和内存问题 - php假设情况:我在php中运行一个复杂的站点,并且我使用了很多全局变量。我可以将变量存储在现有的全局范围内,例如$_REQUEST['userInfo'],$_REQUEST['foo']和$_REQUEST['bar']等,然后将许多不同的内容放入请求范围内(这将是适当的用法,因为这些数据指的是要求自…