"Headers already sent"

I’m trying to setup an API call using Azure OAuth2 but for some reason whenever I try to set the bearer authorization header, I get the following error:

An Error occurred while handling another error:
yii\web\HeadersAlreadySentException: Headers already sent in …/controllers/SiteController.php on line 136. in …/vendor/yiisoft/yii2/web/Response.php:366
Stack trace:
#0 …/vendor/yiisoft/yii2/web/Response.php(339): yii\web\Response->sendHeaders()
#1 …/vendor/yiisoft/yii2/web/ErrorHandler.php(136): yii\web\Response->send()
#2 …/vendor/yiisoft/yii2/base/ErrorHandler.php(123): yii\web\ErrorHandler->renderException(Object(yii\web\HeadersAlreadySentException))
#3 [internal function]: yii\base\ErrorHandler->handleException(Object(yii\web\HeadersAlreadySentException))
#4 {main}
Previous exception:
yii\web\HeadersAlreadySentException: Headers already sent in …/controllers/SiteController.php on line 136. in …/vendor/yiisoft/yii2/web/Response.php:366
Stack trace:
#0 …/vendor/yiisoft/yii2/web/Response.php(339): yii\web\Response->sendHeaders()
#1 …/vendor/yiisoft/yii2/base/Application.php(392): yii\web\Response->send()
#2 …/web/index.php(13): yii\base\Application->run()
#3 {main}

My code:

        $client = new Client(['transport' => 'yii\httpclient\CurlTransport']);
        $response = $client->createRequest(['requestConfig' => ['format' => Client::FORMAT_URLENCODED], 'responseConfig' => ['format' => Client::FORMAT_JSON]])
            ->setMethod('GET')
            ->setHeaders(['Authorization' => 'Bearer ' . $accessToken->params["access_token"]])
            ->setUrl('apiURL.' . '/' . 'command')
            ->setOptions(['SSL_VERIFYPEER' => false, 'SSL_VERIFYHOST' => false, 'FOLLOWLOCATION' => true, 'CUSTOMREQUEST' => 'GET'])
            ->send();

        if ($response->isOk) {
            return $response->data;
        } else {
            echo $response->data['error_msg'];
        }

Does anyone know why I’m having this issue? Ive tried so many different ways (including editing the vendor/yiisoft/yii2-authclient/src/BaseOAuth.php) but nothing is working! Any advice would be greatly appreciated :slight_smile:

Try not to echo anything. In general don’t echo in controllers.