php 怎么响应客户端,php – 根据客户端发送HTML或JSON响应

我有一个带有Eloquent实体的Laravel应用程序及其各自的RESTful resource controllers,如下所示:

该模型

class Entity extends Eloquent {

...

}

控制器

class EntityContoller {

public function index() {

Entity $entities = Entity::all();

return view('entity.index', compact($entities));

}

... // And many more routes like that

}

现在我正在构建一个Android应用程序,而不是返回视图,我需要数据作为JSON.

在我目前的解决方案中,对于我从Android应用程序发出的每个请求,我添加了一个get查询参数contentType = JSON.我在控制器中检测到,并按如下方式相应地发送数据.但这似乎很乏味,我必须在各处写出同样的条件.

class EntityContoller {

public function index() {

Entity $entities = Entity::all();

if(Request::get('contentType', 'JSON')) return $entities;

return view('entity.index', compact($entities));

}

... // And many more routes like that

}

我能做到这一点的最佳方法是什么,而不必在每个控制器动作中写出这个条件?

解决方法:

如果您不想更改控制器,则可以使用middleware在从控制器返回响应后更改响应.

中间件将从控制器接收响应,检查contentType == JSON,然后返回正确的响应.

中间件看起来像这样:

use Closure;

class JsonMiddleware {

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

// Get the response from the controller

$response = $next($request);

// Return JSON if necessary

if ($request->input('contentType') == 'JSON') {

// If you want to return some specific JSON response

// when there are errors, do that here.

// If response is a view, extract the data and return it as JSON

if (is_a($response, \Illuminate\View\View::class)) {

return response()->json($response->getData());

}

}

return $response;

}

}

然后,您将在app / Http / Kernel.php中注册中间件,方法是将其附加到$routeMiddleware数组中.

protected $routeMiddleware = [

'auth' => \App\Http\Middleware\Authenticate::class,

'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,

'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,

// New Middleware

'json' => \App\Http\Middleware\JsonMiddleware::class,

];

然后,您只需将中间件分配给可能返回JSON的路由.

Route::get('user/{user_id}', ['middleware' => 'json', 'uses' => 'App\UserController@getUser']);

您可以阅读有关中间件here以及注册和分配中间件here的更多信息.

您可以阅读有关在Laravel here中发送JSON响应的信息.

标签:php,rest,laravel,laravel-5

来源: https://codeday.me/bug/20190528/1169241.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值