Jeremy
Jeremy

Reputation: 3809

CakePhp is returning HTML and BODY tags along with the json?

I am trying to return plain old JSON but for some reason it is being returned like this:

<html>
   <body>
       {
          "token":"MTEyLSQyeSQxMCRHVS9nS2t2QVRVcGpJWjJGVERldXouWWJFTzgyZ0lCTURBZFIvdWs2RldGNm1IeWxxNGpTUw==",
          "user":{
              "id":112,
              "username":"admin",
              "firstName":"admin",
              "lastName":"admin",
           },
           "userType":{
              "id":1,
              "name":"admin"
           }
       }
   </body>
</html>

I am currently using CakePHP to send the response:

/**
 * @param $controller \App\Controller\AppController
 */
public function respond($controller) {
    $controller->response->header('Content-Type: application/json');
    $controller->response->statusCode($this->statusCode);
    $controller->response->body(json_encode($this->messages));
}

But I have also tried using plain PHP:

echo json_encode($this->messages);
die();

The HTML tags are not problems for my front end, they seem to be ignored by javascript. But some reason TestNG is getting the HTML tags and making the response non-parseable.

Any ideas?

Upvotes: 1

Views: 1256

Answers (1)

Sharfaraz Bheda
Sharfaraz Bheda

Reputation: 457

Use this code to get Json Response:

public function respond($controller) {
    $controller->autoRender = false;
    $this->response->type('json');
    $controller->response->statusCode($this->statusCode);
    $controller->response->body(json_encode($this->messages));
}

Ref. Sending correct JSON content type for CakePHP

Upvotes: 1

Related Questions