处理另一个错误时发生错误:yii \ web \ HeadersAlreadySentException:标头已发送

问题描述

我正在使用yii2开发rest api Web服务。 作为localhost上的json响应,json的空对象结尾响应我。 并在主机上以json结束错误

在localhost中,我收到的响应如下: 在本地主机上响应:

{
    "status": 1,"data": {
        "data": "Factor Api"
    }
}null

但是在服务器上,我收到的响应如下: 服务器上的响应:

{
    "status": 1,"data": {
        "data": "Factor Api"
    }
}<pre>An Error occurred while handling another error:
yii\web\HeadersAlreadySentException: Headers already sent in /home/factorap/public_html/common/components/Api.PHP on line 53. in /home/factorap/public_html/vendor/yiisoft/yii2/web/Response.PHP:366
Stack trace:
#0 /home/factorap/public_html/vendor/yiisoft/yii2/web/Response.PHP(339): yii\web\Response-&gt;sendHeaders()
#1 /home/factorap/public_html/vendor/yiisoft/yii2/web/ErrorHandler.PHP(136): yii\web\Response-&gt;send()
#2 /home/factorap/public_html/vendor/yiisoft/yii2/base/ErrorHandler.PHP(135): yii\web\ErrorHandler-&gt;renderException(Object(yii\web\HeadersAlreadySentException))
#3 [internal function]: yii\base\ErrorHandler-&gt;handleException(Object(yii\web\HeadersAlreadySentException))
#4 {main}
PrevIoUs exception:
yii\web\HeadersAlreadySentException: Headers already sent in /home/factorap/public_html/common/components/Api.PHP on line 53. in /home/factorap/public_html/vendor/yiisoft/yii2/web/Response.PHP:366
Stack trace:
#0 /home/factorap/public_html/vendor/yiisoft/yii2/web/Response.PHP(339): yii\web\Response-&gt;sendHeaders()
#1 /home/factorap/public_html/vendor/yiisoft/yii2/base/Application.PHP(656): yii\web\Response-&gt;send()
#2 /home/factorap/public_html/common/components/Api.PHP(56): yii\base\Application-&gt;end()
#3 /home/factorap/public_html/api/controllers/SiteController.PHP(92): common\components\Api-&gt;sendSuccessResponse(Array)
#4 [internal function]: api\controllers\SiteController-&gt;actionIndex()
#5 /home/factorap/public_html/vendor/yiisoft/yii2/base/InlineAction.PHP(57): call_user_func_array(Array,Array)
#6 /home/factorap/public_html/vendor/yiisoft/yii2/base/Controller.PHP(180): yii\base\InlineAction-&gt;runWithParams(Array)
#7 /home/factorap/public_html/vendor/yiisoft/yii2/base/Module.PHP(528): yii\base\Controller-&gt;runAction(&#039;&#039;,Array)
#8 /home/factorap/public_html/vendor/yiisoft/yii2/web/Application.PHP(103): yii\base\Module-&gt;runAction(&#039;&#039;,Array)
#9 /home/factorap/public_html/vendor/yiisoft/yii2/base/Application.PHP(386): yii\web\Application-&gt;handleRequest(Object(yii\web\Request))
#10 /home/factorap/public_html/api/v2/index.PHP(17): yii\base\Application-&gt;run()
#11 {main}</pre>
第53行的

common / components / Api.PHP = $ this-> setHeader(200);

我发送回复功能: api函数

    public function sendSuccessResponse($data = false,$additional_info = false)
    {

        $this->setHeader(200);

        $response = [];
        $response['status'] = 1;

        if (is_array($data))
            $response['data'] = $data;

        if ($additional_info) {
            $response = array_merge($response,$additional_info);
        }

        $response = Json::encode($response,JSON_PRETTY_PRINT);
        //$strpos = strpos($response,'null');


        if (isset($_GET['callback'])) {
            /* this is required for angularjs1.0 client factory API calls to work */
            $response = $_GET['callback'] . "(" . $response . ")";

            echo $response;
        } else {
            echo $response;
        }

        Yii::$app->end();

    }

和要执行的控制器操作。 控制器动作:

    public function actionIndex()
    {
        Yii::$app->api->sendSuccessResponse(['data' => 'Factor Api']);
    }

请帮助我修复它们。

解决方法

还有另一种方法。像这样:frontend/controllers/ApiController.php

class ApiController extends \yii\rest\Controller
{
    public function behaviors()
    {
        return [
            'contentNegotiator' => [
                'class'   => \yii\filters\ContentNegotiator::className(),'formats' => [
                    'application/json' => yii\web\Response::FORMAT_JSON,],];
    }

    public function actionApi()
    {
        $model = \common\models\User::find()->one();

        return $model->getAttributes();
    }
}

frontend/config/main.php

return [
    // other code
    'components'          => [
        // other code
        'request'      => [
            'enableCookieValidation' => true,'cookieValidationKey'    => 'Ci@1ouPTLKXn9s6myzsfsef2UtTfKwjpnWO','parsers'                => [
                'application/json' => 'yii\web\JsonParser','urlManager'   => [
            'enablePrettyUrl'     => true,'enableStrictParsing' => true,'showScriptName'      => false,'rules'               => [
                '<controller:\w+>/<action:\w+>' => '<controller>/<action>',['class' => 'yii\rest\UrlRule','controller' => 'api'],// other code
    ],];

打开http://yoursite.com/api/users

{
    id: 1,username: "admin",auth_key: "IVi31eKxa-EE3ki7X7ToKb6uO8dknNrV",password_hash: "$2y$13$oMiNRYUYb0gPcWpheiYdb.0Xs/lWk7Ixcb.F5ch38ExbiSok1TfRi",password_reset_token: null,email: "admin@admin.lc",status: 10,created_at: 1603274263,updated_at: 1603274263,verification_token: "cTnvRiub3BpoCEwx-yFUb10zCtu0TpxK_1603274263",}