For my extbase-based TYPO3 CMS extension I created an ApiController with JsonView as view object. Returning values works like a charm, the correct header Content-type: application/json
is set.
To return other responses like missing authorization messages or validation errors, I currently use:
$data = ["errors" => [
"status" => 401,
"message" => "Missing access token"
]];
$this->throwStatus($status, null, json_encode($data));
When I use $this->throwStatus()
the header Content-type: text/html
is set. Even if I manually set header("Content-type: application/json");
before using $this->throwStatus()
.
How can I create responses with the correct content type header?
Before you throw the status, try to set the headers in the response object:
$this->response->setHeader('Content-Type', 'application/json', true);
$this->response->sendHeaders();
If you are accessing your data through a dedicated pageType, you can set the header for this pageType in TypoScript:
myPageType.config.additionalHeaders {
10 {
header = Content-Type: application/json
replace = 1
}
}
I will add this to my post about the topic: https://usetypo3.com/json-view.html