douyaosi3164 2017-04-12 17:26
浏览 39
已采纳

基于标题的路由与Slim 3

I have a Slim 3 route: $app->get('/calendar/{date}', 'CalendarCtrl:getSchedule');
This route can return the same schedule by simple HTML list, json or xml format.
Now I'm looking for a simple REST solution based on Accept (or more headers) HTTP header.

For example:
Request:

GET /calendar/2017-01-01  
Accept: application/json

Response:

Content-Type: application/json
Body: {json schedule}

So a route should be smth like this: $app->get('/calendar/{date}', {Accept: application/json}, 'CalendarCtrl:getScheduleJson');

I know I can check for that header in a route handler. But I'm looking for a simple declarative solution.

  • 写回答

1条回答 默认 最新

  • dtwupu6414 2017-04-13 11:56
    关注

    Add a middleware to check for that header before sending the response from your API

    $app->add(function ($req, $res, $next) {
    //Checking for $req content-type here then send the response with the same one 
    //example 
    $headerValue= $req->getHeader('Accept');
    if($headerValue=='application/json')
    {
      $response = $next($req, $res);
        return $response
                ->withHeader('Content-type', 'application/json');
     }
    else{
    
    //check for other header here  
    }      
    });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
  • ¥15 安装svn网络有问题怎么办