Welcome Guest, Not a member yet? Register   Sign In
JSON formatting in the browser (missing headers)?

I'm responding from an API using this:

return $this->setResponseFormat('json')->respond(json_encode($response), 200);

Now, I would 'expect' the proper headers would be set 'automagically' by doing this ... but NOTHING but the data is sent to the browser (no headers for some reason).

What is the 'hack' I need to use to make CI4 send the proper headers without me having to muck around with it?

This is extending the RerourceController ... if that matters.

PHP Code:
return $this->setResponseFormat('json')->respond(['error' => false]); 
respond($data[, $statusCode=200[, $message='']])
$data (mixed) – The data to return to the client. Either string or array.
$statusCode (int) – The HTTP status code to return. Defaults to 200
$message (string) – A custom “reason” message to return.

Thanks, but that's just what I already did. This does NOT send a header of type json to the client. I had to do this for that to work: return $this->response->setJSON($this->model->find($id));

Now, to me that is a completely different way to do things ... and again; the docs are confusing.

PHP Code:
return $this->setResponseFormat('json')->respond(['error' => false]); 
// equal
return $this->response->setJSON(['error' => false]);  

PHP Code:
// setResponseFormat($format) 
$this->format strtolower($format);

// respond($data) 
// $output contains json if $data not a string
if ($this->format === 'json')
    return $this->response->setJSON($output)->setStatusCode($status$message);

example code with browser output (pic, CI4.1 php 7.3) https://yadi.sk/i/VBFIGIaF-TLF2g

You can actually use setJSON() if you're comfortable.
I'm just showing that the example from the documentation works.

And by the way, when you passed the JSON string in the first example, the header was setted to text/html
link to code

Theme © iAndrew 2016 - Forum software by © MyBB