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']);
Controller :
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 。每次响应时都会生成一个 token ,然后后续的请求预计会沿着该 token 发送。如果 token 匹配,则一切正常,如果不匹配(或者请求根本不提供 token ),则这可能是 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
或作为名为X- 的 HTTP header CSRF-TOKEN
。您可以使用辅助函数csrf_token()
获取它:
``
.ajax({
url: url,
data : {comment_id:comment_id, "_token":"{{ csrf_token() }}"},
type: "POST",
dataType: "json",
....
});
关于php - 在 laravel 5 中发送 ajax 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31213905/