【问题标题】:Laravel: TokenMismatchException while send form to databaseLaravel:将表单发送到数据库时出现 TokenMismatchException
【发布时间】:2016-10-07 10:27:50
【问题描述】:

当我尝试在 laravel 中保存表单中的数据时,总是会出现此错误:

VerifyCsrfToken.php 第 68 行中的 TokenMismatchException:

但是当我通过 apache 访问 laravel 时出现错误,当我通过命令 php artisan serve --host 0.0.0.0 运行 laravel 服务器时,它运行良好...

这是我的表单视图:

<form class="" method="POST" action="{{ $card->path() }}/notes">
    <input type="hidden" name="_token" value="{{ csrf_token() }}">
    <div class="form-group">
        <textarea name="body" class="form-control" rows="8" cols="40"></textarea>
    </div>
    <div class="form-group">
        <button type="submit" class="btn btn-primary" name="button">Dodaj</button>
    </div>
</form>

这是我的控制器:

<?php

namespace App\Http\Controllers;

use App\Card;
use App\Note;
use Illuminate\Http\Request;

use App\Http\Requests;

class NotesController extends Controller
{
   public function store(Request $request, Card $card)
   {
      $card->notes()->save(
         new Note(['body' => $request->body])
      );

      return back();
    }
}

这是我的函数,它会在成功发送表单到数据库后重定向用户:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Card extends Model
{
    //
    public function notes()
    {
       return $this->hasMany(Note::class);
    }

    public function path()
    {
        return '/cards/' . $this->id;
    }
}

【问题讨论】:

  • 你能显示你的路线吗?
  • Route::get('cards/{card}', 'CardsController@show'); Route::post('cards/{card}/notes', 'NotesController@store'); 这里
  • 你把它放在你的网络路由组里了吗?
  • 是的,这是在routes/web.php

标签: php laravel token


【解决方案1】:

在标题中添加这一行

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

【讨论】:

  • 这没有改变:(
【解决方案2】:

在表单标签{{ csrf_field() }}之后添加这个

【讨论】:

  • 这个我得到同样的错误,只适用于 laravel 服务器。
【解决方案3】:

在 Laravel 中,最佳实践是使用 Blade 来表示表单。它将自己创建令牌。

{!! Form::open(['action'=>$card->path().'/notes','method'=>'post']) !!}
    // fields and buttons
{!! Form::close() !!}

【讨论】:

  • 其实在本期c中并没有什么不同。
【解决方案4】:

你首先清除你的视图

php artisan view:clear

然后把你的观点写成这样

<form class="" method="POST" action="{{ $card->path() }}/notes">
{!! csrf_field() !!}
    <div class="form-group">
        <textarea name="body" class="form-control" rows="8" cols="40"></textarea>
    </div>
    <div class="form-group">
        <button type="submit" class="btn btn-primary" name="button">Dodaj</button>
    </div>
</form>

这可能会解决您的问题

【讨论】:

  • 如果您使用{!! csrf_field() !!},则不再需要_token 的另一个输入字段
【解决方案5】:

我有同样的问题,通过清除视图缓存:php artisan view:clear,然后将存储文件夹更改为 777 不是 775 来修复它。

【讨论】:

    猜你喜欢
    • 2018-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-15
    • 2017-07-06
    • 2014-01-20
    • 2016-01-27
    相关资源
    最近更新 更多