Laravel5: TokenMismatchException in compiled.php l

2019-06-04 10:18发布

THE SITUATION:

Sorry in advance if it has already been asked. But no matter what I can never make it works.

I am using Laravel 5 as API.

I have a simple function to edit a task.

I am testing it through my web app or through Postman.

I am always getting this error:

TokenMismatchException in compiled.php line 3123:

TokenMismatchException

THE CODE:

The function:

public function updateTask(Request $request)
{
    $id = $request->input('id');

    $task = Task::find($id);
    $task->name = $request->input('name');
    $task->type = $request->input('type');
    $task->save();

    return $task;
}

The route:

Route::group(['middleware' => ['web']], function () {

    Route::post('update', 'TaskController@updateTask');
});

THE QUESTION:

Why I am getting that error?

4条回答
淡お忘
2楼-- · 2019-06-04 10:29

I solved it by inserting the route name as an item in the array $except in the file:

app/http/Middleware/VerifyCsrfToken.php

Like this:

/**
 * The URIs that should be excluded from CSRF verification.
 *
 * @var array
 */
 protected $except = [

     'update'
 ];
查看更多
何必那么认真
3楼-- · 2019-06-04 10:34

Try to add this in your form:

<input type="hidden" name="_token" value="{{ csrf_token() }}">
查看更多
放我归山
4楼-- · 2019-06-04 10:42

It works from your web app because your web app is passing the token.

You need to open up app/Http/Kernel.php and comment out \App\Http\Middleware\VerifyCsrfToken::class,. However this will leave your site vulnerable to CSRF attacks so you should also find another way to protect your site.

My suggestion would be to keep the CSRF middleware and create a new route group with a prefix of your choice ( usually something like api/v1/ ) which is outside the web middleware group. These routes would then not be protected by CSRF so you should find another way to protect them. I've recently had a lot of success doing this exact same thing with jwt-auth. https://github.com/tymondesigns/jwt-auth

Of course, if your front end is not completely decoupled with your backend and Laravel is outputting the initial page which is then later controlled by angular, you can drop the CSRF token into a meta tag and grab it later with angular and pass it in the header X-CSRF-TOKEN, then Laravel will pick it up.

查看更多
女痞
5楼-- · 2019-06-04 10:49

You need to pass this in your headers;

headers: {
    'X-CSRF-TOKEN': {{ csrf_token() }}
},
查看更多
登录 后发表回答