通过外部类修改Slim 3中的响应对象

时间:2017-08-30 02:57:11

标签: php header response slim

我的瘦身应用程序存在问题,我想发送json响应但是有自定义标题。我的代码如下:

的index.php

require 'vendor/autoload.php';
require 'app/config.php';
require 'app/libs/api.cs.php';

$app = new Slim\App(    
    [
        "settings" => $config,
        "apics" => function() { return new APIHelper(); } //This is a class that contain a "helper" for api responses
    ]
  );

require 'app/dependences.php';
require 'app/middleware.php';
require 'app/loader.php';
require 'app/routes.php';

// Run app
$app->run();

app / libs / api.cs.php("帮助")

<?php
class APIHelper
{
    public function sendResponse($response, $status='success' ,$code = 200, $message = "", $data = null)
    {
      $arrResponse = array();  
      $arrResponse['status'] = $status;
      $arrResponse['code'] = $code;
      $arrResponse['message'] = $message;  
      $arrResponse['data'] = $data;
       return $response
        ->withHeader('Access-Control-Allow-Origin', '*')
        ->withHeader('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type, Accept, Origin, Authorization, AeroTkn')
        ->withHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
        ->withHeader('Content-Type','application/json')
        ->withHeader('X-Powered-By','My API Server')
        ->withJson($arrResponse,$code);
    }
}

我的路线档案(app / routes.php)

$app->group('/foo', function () {
  $this->get('', function ($req, $res, $args) {
    return $this->apics->sendResponse($res, 'success' ,200, "Foo API Index By Get", null);
});

  $this->post('', function ($req, $res, $args) {
    try{
        $oBody = $req->getParsedBody();
        return $this->apics->sendResponse($res, 'success' ,200, "Foo API POST Response", $oBody);        
      }
      catch(\Exception $ex){
        return $this->apics->sendResponse($res, 'error' ,500, "Process Error", array('error' => $ex->getMessage()));
    }   
  });
});

当我尝试使用请求正文运行我的应用时,结果如下: 头:

connection →Keep-Alive
content-type →text/html
date →Wed, 30 Aug 2017 02:22:56 GMT
keep-alive →timeout=2, max=500
server →Apache
transfer-encoding →chunked

Body(以简单文本形式返回,而不是json编码)

{"status":"success","code":200,"message":"Foo API POST Response","data":{"one":"1", "two":"2"}}

我尝试将这个类作为中间件,但我对这些主题感到困惑。

你能帮我告诉我这些方法是好还是我不好。

感谢所有人,我希望你的答案!美好的一天

2 个答案:

答案 0 :(得分:0)

使用中间件是解决问题的理想方法

只需在middeleware文件中添加此功能

 $app->add(function ($req, $res, $next) {
        $response = $next($req, $res);
        return $response
        ->withHeader('Access-Control-Allow-Origin', 'http://mysite')
        ->withHeader('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type, Accept, Origin, Authorization')
         ->withHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
         ->withHeader('Content-Type','application/json');
        ->withHeader('X-Powered-By','My API Server');
    });

答案 1 :(得分:0)

我发现了&#34;错误&#34;是一个幼儿园问题哈哈哈,我从网络服务器下载我的所有代码,在我的机器上测试,我有相同的结果,但我发现我的所有文件在开始时都有奇怪的字符,所以我重新保存文件为utf-8,问题解决了。可以造成头痛的小细节!感谢Nica和Ramy。 Ramy:解决方案非常好,现在代码更加组织化,我采取这种做法。祝大家好日子。