带有中间件的控制器和控制器中的返回响应在 Laravel 5.1 中不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32083762/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 12:12:51  来源:igfitidea点击:

Controller with Middleware and return response in the controller not working in Laravel 5.1

phplaravellaravel-5.1

提问by chemitaxis

I am programming a Laravel 5.1 RestFUL API, but I have a very strange problem with the middleware and the controller response (is empty always).

我正在编写 Laravel 5.1 RestFUL API,但中间件和控制器响应(始终为空)有一个非常奇怪的问题。

Routes:

路线:

Route::group(['prefix' => 'api/v1', 'middleware' => 'token.api'], function () {

    Route::post('game/add/{id}', 'GameController@addGameToUser');    
});

The middleware is defined in the kernel.php correctly:

中间件在 kernel.php 中正确定义:

protected $routeMiddleware = [
        'auth' => \App\Http\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'token.api' => \App\Http\Middleware\TokenMiddleware::class,
    ];

I have removed

我已经删除

\App\Http\Middleware\VerifyCsrfToken::class

\App\Http\Middleware\VerifyCsrfToken::class

from the middlewares globals, because I just use AJAX API calls. ,

来自中间件全局变量,因为我只使用 AJAX API 调用。,

In my middleware, I check just I have a Token header param:

在我的中间件中,我检查了我是否有一个 Token 标头参数:

Middleware Code:

中间件代码:

<?php

namespace App\Http\Middleware;
use Closure;

class TokenMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {

        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
        header('Access-Control-Allow-Headers: Origin, Content-Type, Token, Accept, Authorization, X-Request-With');
        header('Access-Control-Allow-Credentials: true');


        $token = $request->header('Token');

        if($token == null)
            return response('Not valid token provider.', 401);

        else
        {
            $next($request);
        }



    }
}

In my controller (GameController), and in the method addGameToUser, I just return a JSON Test value, but the response is always empty (testing with postman). If I remove the middleware from the controller, all works fine... I have no idea why...

在我的控制器 (GameController) 和方法 addGameToUser 中,我只返回一个 JSON 测试值,但响应始终为空(使用邮递员测试)。如果我从控制器删除中间件,一切工作正常..。我不知道为什么...

Controller Code:

控制器代码:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;



use App\Http\Controllers\Controller;
use App\UserGame;

class GameController extends Controller
{
    public function addGameToUser(Request $request, $idGame)
    {
        return response()->json(['status'=>'ok','data'=>'data_example'], 200);
    }

}

Thank you so much!!

非常感谢!!

回答by John Bupit

You're not returning anything in handle()if $tokenisn't null. Try this:

handle()如果$token不为空,您不会返回任何内容。尝试这个:

public function handle($request, Closure $next)
{

    header('Access-Control-Allow-Origin: *');
    ...

    $token = $request->header('Token');

    if($token == null) return response('Not valid token provider.', 401);

    // return the $next closure, so other Middlewares can run
    return $next($request);
}

回答by mdamia

You forgot to return the response. just add return as below.

您忘记返回响应。只需添加返回如下。

return $next($request);

Hope this help.

希望这有帮助。

回答by Imtiaz Pabel

Don't remove VerifyCsrfToken.phpit's used for security purpose.There is some way to avoid CSRF.You can avoid an full route and can also can avoid specific url.For this first go to VerifyCsrfToken.phpand edit like this

不要删除VerifyCsrfToken.php,它用于安全目的。有一些方法可以避免CSRF。您可以避免完整路由,也可以避免特定url。为此首先转到VerifyCsrfToken.php并像这样编辑

If want avoid routes try this

如果想避开路线试试这个

//add an array of Routes to skip CSRF check


private $openRoutes = ['free/route', 'free/too'];

//modify this function

//修改这个函数

public function handle($request, Closure $next)
{
    //add this condition 
foreach($this->openRoutes as $route) {

  if ($request->is($route)) {
    return $next($request);
  }
}

return parent::handle($request, $next);
}

Hope it will work

希望它会起作用