在laravel 5中发送ajax请求

Kio*_*Key 1 php ajax jquery laravel-5

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);
                }

            });
Run Code Online (Sandbox Code Playgroud)

路线:

Route::post('/ajaxSend', ['as'=> 'ajaxSendmsg', 'uses'=>'PostsController@ajaxSend']);
Run Code Online (Sandbox Code Playgroud)

控制器:

public  function ajaxSend(){

        if( Request::ajax() ){

        return Response::json(['success' => 1]);
        }

    }
Run Code Online (Sandbox Code Playgroud)

错误:VerifyCsrfToken.php第53行中的TokenMismatchException:

我正在尝试发送ajax请求,但它不起作用.:/

Qua*_*unk 5

默认情况下,Laravel在非读取HTTP请求(如POST,PUT或PATCH)上有一个中间件,以防止跨站点请求伪造.在每个响应中,生成一个令牌,然后期望后续请求沿该令牌发送.如果令牌匹配,一切都很好,如果没有(或者如果请求根本没有提供令牌),这可能是CSRF漏洞利用.

有几种方法可以解决这个问题:

  1. 通过评论来完全禁用中间件app/Http/Kernel.php- 显然不是最好的主意.
  2. 通过使用您自己的默认中间件覆盖默认中间件,仅对您确定不需要它的路由禁用它:

``

<?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);
    }
}
Run Code Online (Sandbox Code Playgroud)
  1. 只需在请求体中_token,在请求字符串中_token或作为名为的HTTP头的每个请求中发送它X-CSRF-TOKEN.您可以使用辅助函数来获取它csrf_token():

``

.ajax({
   url: url,
   data : {comment_id:comment_id, "_token":"{{ csrf_token() }}"},
   type: "POST",
   dataType: "json",
   ....
});
Run Code Online (Sandbox Code Playgroud)