How can I parse my JSON sent through POST method with NO Content Header? When I set Content Header as application/json, getParsedBody() method is able to parse the json and convert it an array. But when no Content Header is set in the request, it is not able to parse.
If you’re having issues parsing with javascript, try:
myObj = typeof myObj == ‘string’ ? JSON.parse(myObj) : myObj; // convert to an object if it’s a string
mybe this can help you,
public function __invoke(Request $request, Response $response, $args)
{
$body = $request->getBody();
$content = (array)json_decode($body->getContents();
}
You can also set the Content-Type header in the request if it is missing using middleware:
$app->post('/test', function($request, $response, $args) {
$body = $request->getParsedBody();
// ...
})->add(function($request, $response, $next) {
// set application/json as content-type if no content type is set
if (!$request->hasHeader('Content-Type')) {
$request = $request->withHeader('Content-Type', 'application/json');
}
return $next($request, $response);
});