Laravel REST API请求对象为空。

4

环境

我使用Laravel 5.7创建了一个应用程序并实现了REST API。我在routes/api.php中创建了一个路由,触发一个中间件,检查传入的请求是否有一个名为api_token的参数。

这是一个生产环境,以下是具体信息:

  • Linux Ubuntu 18.04 LTS 64位
  • nginx/1.14.0
  • Laravel 5.7
  • PHP 7.2

.env文件中的APP_ENV设置为“production”,APP_DEBUG设置为“false”。

问题

我的问题是当传入请求到达服务器时,请求对象总是为空。至少这是我的Laravel应用程序说的。

这是我在routes/api.php中的路由:

Route::middleware('rest')->group(function() {
    Route::get('device-location/{deviceID}', 'PositionDataController@getDeviceLocation');
    Route::get('device-location/all', 'PositionDataController@getAllLocations');
    Route::post('device-location', 'PositionDataController@storeDeviceLocation');
    Route::put('device-location/{deviceID}', 'PositionDataController@updateDeviceLocation');
    Route::delete('device-location/{deviceID}', 'PositionDataController@deleteDeviceLocation');
});

路由在一个名为“rest”的中间件组中,如您所见。我正在使用Route::get('device-location/{deviceID}', 'PositionDataController@getDeviceLocation');路由来测试功能。
以下是中间件的代码:
public function handle($request, Closure $next)
{
    if(request()->all()) {
        $deviceID = request()->device_id;
    }
    else {
        return response()->json([
            'error' => 'The request object is empty.',
            'request' => request(),
            'parameters' => request()->all(),
            'content' => request()->getContent(),
            'input' => request()->input()
        ], 500);
    }

    $device = MobileDevice::where('device_id', $deviceID)->first();

    if($device) {
        $deviceToken = $device->api_token;
        if($deviceToken == request()->api_token) {
            return $next($request);
        }
        else {
            return response()->json(['error' => 'Token does not match.'], 500);
        }
    }
    else {
        return response()->json(['error' => 'The device with the id [' . $deviceID . '] could not be found.'], 500);
    }
}

中间件首先检查请求对象中是否有参数,然后执行一些逻辑以检查是否发送了正确的令牌。如果请求对象为空,则返回一些数据以帮助我了解出了什么问题。
我使用Postman(https://www.getpostman.com)测试API。这是我的Postman设置: Postman设置

Screen Shot

Postman 标头

Screen Shot

这是我在Postman中收到的响应:
Postman响应

Screen Shot

如果我在浏览器中调用该路由,将会得到相同的结果。无论是否输入参数,请求似乎总是为空。

以下是我尝试过的方法:

  • 不使用中间件
  • 使用$request变量而不是helper request()
  • 在Postman设置的Headers中切换'application/json'和'application/x-www-form-urlencoded'
  • 在浏览器中调用该路由
  • 升级到Laravel 5.7

奇怪的是,所有这些在我的本地环境和与生产服务器具有相同规格的测试服务器上都可以完美运行。

更新01:

看起来情况更糟了...

如果我在web.php中添加以下路由:

Route::get('/request-return', function() {
    return request()->all();
});

并像这样访问该路由:

laravel.application/request-return?device_id=1&api_token=XgkQLs8G7OYTqdwsXmjJT5G9bxv20DRi

我得到了一个空数组[]。
所以看起来参数没有传输到服务器本身。
2个回答

1

您正在通过GET请求获取设备ID,因此请使用以下行而不是$request()->device_id

请使用以下内容并让我知道 $name = $request->input('device_id')


1
所以,如果我在中间件的顶部添加$name = $request->input('device_id'); return ['name' => $name];我会得到这个响应:{ "name": null } - user10814616

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接