2017-03-01 93 views
0

我犯了一個頁面視圖/ maessage.php
https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js「> TokenMismatchException在VerifyCsrfToken.php線53

<script> 
    function getMessage(){ 
     $.ajax({ 
      type:'POST', 
      url:'/getmsg', 
      data:{'_token': '{{ csrf_token() }}'}, 
      success:function(data){ 
       $("#msg").html(data.msg); 
      } 
     }); 
    } 
    </script> 
    <body> 
    <div id = 'msg'>This message will be replaced using Ajax. 
    Click the button to replace the message.</div> 
    <?php 
    echo Form::button('Replace Message',['onClick'=>'getMessage()']); 
    ?> 
    </body> 
在routes.php文件

Route::get('/ajax',function(){ 
    return view('message'); 
}); 

路線::交

( '/的getMsg', 'AjaxController @索引');在

AjaxController.php
namespace App\Http\Controllers; 

use Illuminate\Http\Request; 

use App\Http\Requests; 
use App\Http\Controllers\Controller; 

class AjaxController extends Controller 
{ 
    public function index(){ 
    $msg = "This is a simple message."; 
    return response()->json(array('msg'=> $msg), 200); 
    } 
} 

,當我跑http://localhost:8000/ajax http://localhost:8000/getmsg產生以下錯誤

哎呦,看起來像出事了。

1/1 MethodNotAllowedHttpException在RouteCollection.php行218:在 RouteCollection.php線218和錯誤的布赫.....

,但是當我在CONSOL看到它顯示下面的錯誤

TokenMismatchException在VerifyCsrfToken.php線53:在 VerifyCsrfToken.php線53

我不明白錯誤。我在laravel更新鮮。而我實際上不知道'_token'的含義:'{{ csrf_token() }}'在message.php中。請。有助於解決這個錯誤。

回答

0

此異常:

MethodNotAllowedHttpException

告訴你,你的窗體上的方法是不一樣的路線上的方法。

所以你有2個選項來解決這個問題。

第一種選擇:更改路線方法類型 您的路線有一個GET

Route::get('/ajax',function(){ 
    return view('message'); 
}); 

但在窗體中有一個POST

所以將其更改爲:

Route::post('/ajax',function(){ 
    return view('message'); 
}); 

二選項:更改您的ajax表單方法類型

Route::get('/ajax',function(){ 
    return view('message'); 
}); 


    <script> 
    function getMessage(){ 
     $.ajax({ 
      type:'GET', 
      url:'/getmsg', 
      data:{'_token': '{{ csrf_token() }}'}, 
      success:function(data){ 
       $("#msg").html(data.msg); 
      } 
     }); 
    } 
    </script> 

關於您關於CSRF的問題。它可以防止跨站點僞造。你可以在這裏閱讀:https://laravel.com/docs/5.4/csrf

+0

雅,我讀了那頁,但我無法得到更多的東西。 –

相關問題