Yii2 報錯 Headers already sent in


有時候我們把Yii2 版本進行升級之后 會報一些莫名其妙的錯誤,這次就遇到如下錯誤信息

an Error occurred while handling another error:
exception 

'yii\web\HeadersAlreadySentException' with message 'Headers already sent in /xxxx/xxxx/xxx.php on line 90.' in /xxxx/xxxx/vendor/yiisoft/yii2/web/Response.php:366

Stack trace:
#0 /xxxx/xxxx/vendor/yiisoft/yii2/web/Response.php(339): yii\web\Response->sendHeaders()
#1 /xxxx/xxxx/vendor/yiisoft/yii2/web/ErrorHandler.php(135): yii\web\Response->send()
#2/xxxx/xxxx/vendor/yiisoft/yii2/base/ErrorHandler.php(111):

yii\web\ErrorHandler->renderException(Object(yii\web\HeadersAlreadySentException))

#3 [internal function]: yii\base\ErrorHandler->handleException(Object(yii\web\HeadersAlreadySentException))
#4 {main}


查閱了一些資料說,是因為使用json輸出內容的時候 沒有exit。以前的寫法如下

protected function renderJSON($data=[], $msg ="ok", $code = 200)
{
    header('Content-type: application/json');
    echo json_encode([
        "code" => $code,
        "msg"   =>  $msg,
        "data"  =>  $data,
        "req_id" =>  $this->geneReqId(),
    ]);


    return Yii::$app->end();
}


改成如下

protected function renderJSON($data=[], $msg ="ok", $code = 200)
{
    $response = Yii::$app->response;
    $response->format = Response::FORMAT_JSON;
    $response->data  = [
        "code"   => $code,
        "msg"    => $msg,
        "data"   => $data,
        "req_id" => $this->geneReqId(),
    ];
    return $response;
}



原文地址: Yii2 報錯 Headers already sent in
標簽: yii2    json    header   

智能推薦


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM