laravel 5.2 ajax调用中的TokenMismatchException

时间:2016-03-04 07:23:19

标签: javascript php ajax laravel laravel-5.2

我得到令牌不匹配异常,似乎每件事情都是正确的。

这是我的观看代码

@extends('layouts.master')
@section('content')
<div class="bg"></div>
<div class="login-sec clearfix">

    <h1 class="lg-logo">YOU ARE JUST ONE STEP AHEAD</h1>
    <div class="login-box clear">

        <form id="websiteform" action="#">
            <input type="hidden" name="_token" value="{{ csrf_token() }}">
            <div class="col-md-12 form-field">
                <label for="">Project Name</label>
                <input type="text" name="project" id="project">
            </div>

            <div class="col-md-12 form-field">
                <label for="">Website URL</label>
                <input type="url" name="website_url" id="website_url">
            </div>

            <div class="col-md-12 form-field">
                <button type="submit" class="btn-green btn-large">Add Your Website</button>
            </div>
        </form>

    </div>
</div>
@stop

和表单源头部分和页脚是

  <head>
   <meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
<meta name="csrf-token" content="4ryCSznz0mPSBcwXvbmZZHkZGcxZpyDy2dQ1VAoc" />
<link href="http://localhost:8080/css/bootstrap.min.css" rel="stylesheet" media="screen">

 <script src="http://localhost:8080/js/jquery.min.js"></script>
<script src="http://localhost:8080/js/bootstrap.min.js"></script>
<script src="http://localhost:8080/js/main.js"></script>

和我在main.js中的ajax调用

$(document).ready(function () {

$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});
$('#websiteform').submit(function(e){
    e.preventDefault();
    var pro=$('#project').val();
    var url=$('#website_url').val();

    $.ajax({
        type: "POST",
        url: "project_save",
        data:  {project: pro, url: url},
        success: function(data)
        {
            if(data.success==false)
            {
             alert(data.error);
            }
            else{
                window.location =  "dashboard";
            }
        },
        error:function(){}
    });
});
});

和路线和控制器功能

 Route::post('/project_save','WebsiteController@project_save');
  public function project_save()
{
    if(Request::ajax()){

        $validator = Validator::make(Request::all(), [
            'project' => 'required|max:255',
            'url' => 'required',
        ]);
        if($validator->fails()){
            return Response::json(['success'=>false,'error'=>$validator->errors()->toArray()]);
        }

        $Website = new Website;
        $Website->project_name = Request::get('project');
        $Website->website_url = Request::get('url');
        $Website->user_id = Auth::id();
        $Website->save();
        return Response::json(['success'=>true]);
    }

}

这是我的代码,我得到了tokenmismatach exeption。

4 个答案:

答案 0 :(得分:0)

更改您的\App\Http\Middleware\VerifyCsrfToken.php,将此代码添加到功能tokensMatch

if ($request->ajax()) {
        return true;
    }

答案 1 :(得分:0)

试试这个

$_token = "{{ csrf_token() }}";
$.post( 'myurl', { param1: $param1, param2: $param2, _token: $_token })
  .done(function( data )
{
    console.log('Done!');
});

答案 2 :(得分:0)

如果您不想为特定网址提供CSRF保护,那么您可以在static class MyHandler extends Handler { private final WeakReference<MyFragment> mFragment; public MyHandler(MyFragment fragment) { mFragment = new WeakReference<>(fragment); } @Override public void handleMessage(Message msg) { MyFragment fragment = mFragment.get(); if (fragment != null) { String tempValue = (String) msg.obj; if (tempValue != null && !tempValue.equals("")) { try { fragment.setValuesFromBluetooth(tempValue.trim()); // here i need something to update the current active fragment } } catch (Exception e) { //log } } } } } private void setValuesFromBluetooth(String value) { tv1.setText(value); } 中添加这样的网址

App\Http\Middleware\VerifyCsrfToken.php

答案 3 :(得分:0)

仔细检查以下内容:

我有类似的问题,这很容易解决。

在HTML元标记区域添加:

 <meta name="csrf-token" content="{{ csrf_token() }}">

然后在您的JQuery参考下,添加以下代码:

<script type="text/javascript">
      $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
      });
  </script>

如果您使用HTML表单提交(而不是AJAX),那么您需要输入:

{{ csrf_field() }} 

在表单标记内。