# withJson and Content-Type

**URL:** <https://discourse.slimframework.com/t/withjson-and-content-type/218>\
**Category:** Questions\
**Created:** [May 7, 2016, 2:29pm UTC](https://discourse.slimframework.com/t/withjson-and-content-type/218 "2016-05-07T14:29:57Z")\
**Posts on this page:** 12\
**Page:** 1

<div class="post-metadata">

**Author:** ![ela1979](https://yyz2.discourse-cdn.com/flex030/user_avatar/discourse.slimframework.com/ela1979/32/661_2.png) [@ela1979](https://discourse.slimframework.com/u/ela1979)\
**Post date:** [May 7, 2016, 2:29pm UTC](https://discourse.slimframework.com/t/withjson-and-content-type/218/1 "2016-05-07T14:29:57Z")

</div>

Hello,

I try to convert my development project from Slim v2 to Slim v3 and I have a behavior which i can’t explain the reason why.  
It’s written in the documentation ([http://www.slimframework.com/docs/objects/response.html](http://www.slimframework.com/docs/objects/response.html)) that “The Content-Type of the Response is automatically set to application/json;charset=utf-8.” when we use withJson.

But I have a problem because when i get the response “Content-type” is “text/html; charset=UTF-8”

My code is very simple.

**The route :**

`$app->get("/{memberRole:public|member|moderator|admin|superuser}/members[/{id:[0-9]+}]", '\LPDP\Controllers\membersController:getMembers' )->setName("getMembers");`

**The method**

```
public function get(Request $req, Response $res, $args, $table)
    {
        /**
         * get response error code
         */
        $result = $this->conf->get('errors.REST_RESPONSE_OK');
        $sqlStatement = "SELECT * FROM $table";
        $this->db->exec("SET NAMES utf8");
        $sdata = $this->db->prepare($sqlStatement);
        $sdata->execute();
        $data = $sdata->fetchAll(PDO::FETCH_CLASS);

        /**
         * add debug information in response
         */
        $data["debug"] = "get$table";

        /**
         * return response
         */
        return $res->withJson($data, $result["httpStatus"]);
    }

```

The response property :

```
HTTP/1.1 200 OK
Server: xxxxxxxx
Date: Sat, 07 May 2016 14:04:35 GMT
Content-Type: text/html; charset=UTF-8
Transfer-Encoding: chunked
Connection: keep-alive
Vary: Accept-Encoding
X-Powered-By: PHP/5.5.35
X-Cache: HIT from Backend

```

Have you any idea why I don’t get the correct Content-Type ?

Thanks for your help.

---

<div class="post-metadata">

**Author:** ![dopesong](https://yyz2.discourse-cdn.com/flex030/user_avatar/discourse.slimframework.com/dopesong/32/31_2.png) [@dopesong](https://discourse.slimframework.com/u/dopesong)\
**Post date:** [May 7, 2016, 3:37pm UTC](https://discourse.slimframework.com/t/withjson-and-content-type/218/2 "2016-05-07T15:37:03Z")

</div>

Hey,

You sure it’s copy of your code - because I just tested your code and it returns normal content-type header.

---

<div class="post-metadata">

**Author:** ![ela1979](https://yyz2.discourse-cdn.com/flex030/user_avatar/discourse.slimframework.com/ela1979/32/661_2.png) [@ela1979](https://discourse.slimframework.com/u/ela1979)\
**Post date:** [May 7, 2016, 5:00pm UTC](https://discourse.slimframework.com/t/withjson-and-content-type/218/3 "2016-05-07T17:00:13Z")

</div>

Hi,

Thanks for your answer. I have two middlewares

```
/**
 * define JWT middleware
 */
$app->add(new Slim\Middleware\JwtAuthentication([
    "secure" => false,
    "secret" => "key",
    "rules" => [
        new \Slim\Middleware\JwtAuthentication\RequestPathRule([
            "path" => "/",
            "passthrough" => ["/public"]
        ]),
        new \Slim\Middleware\JwtAuthentication\RequestMethodRule([
            "passthrough" => ["OPTIONS"]
        ])
    ],
    "callback" => function (Request $request, Response $response, $arguments) use ($container) {
        $container["jwt"] = $arguments["decoded"];
    },
    "error" => function (Request $request, Response $response, $arguments) use ($container) {
        //TODO: complete response
        $conf = $container->get('apiConfig');
        $data = $conf->get('errors.REST_RESPONSE_UNAUTHORIZED');
        $data["debug"] = "error-jwt";
        return $response->withJson($data, $data["httpStatus"]);
    }
]));

/**
 * add Authentication Session middleware
 */
$app->add(new \LPDP\Middleware\AuthenticateSession());

```

The AuthenticateSession class is empty (just the invoke function for now without any action).

```
class AuthenticateSession
{
   public function __invoke(ServerRequestInterface $req, ResponseInterface $res, $next)
    {
        $res = $next($req, $res);

        return $res;
    }
}

```

It’s strange… I use the version 3.3.0 (with composer). You are in the same version ?

Thanks you

---

<div class="post-metadata">

**Author:** ![JoeBengalen](https://avatars.discourse-cdn.com/v4/letter/j/b5e925/32.png) [@JoeBengalen](https://discourse.slimframework.com/u/JoeBengalen)\
**Post date:** [May 8, 2016, 9:17am UTC](https://discourse.slimframework.com/t/withjson-and-content-type/218/4 "2016-05-08T09:17:19Z")

</div>

You copied the right code? Because the mapping refers to a method named `getMembers` and the method you posted is named `get`.

---

<div class="post-metadata">

**Author:** ![ela1979](https://yyz2.discourse-cdn.com/flex030/user_avatar/discourse.slimframework.com/ela1979/32/661_2.png) [@ela1979](https://discourse.slimframework.com/u/ela1979)\
**Post date:** [May 8, 2016, 1:21pm UTC](https://discourse.slimframework.com/t/withjson-and-content-type/218/5 "2016-05-08T13:21:15Z")

</div>

Hello

I’ve a class membersController that inherit from a class controller. That’s the reason why you don’t retrieve the good name for the method 😉

```
class membersController extends controller
{

    private $table = "members";

    public function getMembers(Request $req, Response $res, $args)
    {
        parent::get($req, $res, $args, $this->table);
    }
```

---

<div class="post-metadata">

**Author:** ![ela1979](https://yyz2.discourse-cdn.com/flex030/user_avatar/discourse.slimframework.com/ela1979/32/661_2.png) [@ela1979](https://discourse.slimframework.com/u/ela1979)\
**Post date:** [May 8, 2016, 1:29pm UTC](https://discourse.slimframework.com/t/withjson-and-content-type/218/6 "2016-05-08T13:29:40Z")

</div>

I just try to modify my code of membersController :

```
public function getMembers(Request $req, Response $res, $args)
{
    return $res->withJson(parent::get($req, $res, $args, $this->table));
} 

```

It’s same result 😕 :

```
HTTP/1.1 200 OK
Server: xxx
Date: Sun, 08 May 2016 13:25:44 GMT
Content-Type: text/html; charset=UTF-8
Transfer-Encoding: chunked
Connection: keep-alive
Vary: Accept-Encoding
X-Powered-By: PHP/5.5.35
X-Cache: HIT from Backend
```

---

<div class="post-metadata">

**Author:** ![JoeBengalen](https://avatars.discourse-cdn.com/v4/letter/j/b5e925/32.png) [@JoeBengalen](https://discourse.slimframework.com/u/JoeBengalen)\
**Post date:** [May 9, 2016, 7:55am UTC](https://discourse.slimframework.com/t/withjson-and-content-type/218/7 "2016-05-09T07:55:59Z")

</div>

> [@ela1979](#):
>
> `parent::get($req, $res, $args, $this->table);`

You don’t return the response here, you just call the parent. You should put `return` before `parent`.

---

<div class="post-metadata">

**Author:** ![ela1979](https://yyz2.discourse-cdn.com/flex030/user_avatar/discourse.slimframework.com/ela1979/32/661_2.png) [@ela1979](https://discourse.slimframework.com/u/ela1979)\
**Post date:** [May 11, 2016, 12:32am UTC](https://discourse.slimframework.com/t/withjson-and-content-type/218/8 "2016-05-11T00:32:21Z")

</div>

hi,  
I tried this but same issue. I will try to rewrite my code step by step to identify the root cause and I will give you the results.

I am very busy on other things this week . I will do this weekend

thank you

---

<div class="post-metadata">

**Author:** ![zeroxx1986](https://yyz2.discourse-cdn.com/flex030/user_avatar/discourse.slimframework.com/zeroxx1986/32/94_2.png) [@zeroxx1986](https://discourse.slimframework.com/u/zeroxx1986)\
**Post date:** [May 11, 2016, 7:32am UTC](https://discourse.slimframework.com/t/withjson-and-content-type/218/9 "2016-05-11T07:32:22Z")

</div>

Hello,  
I think have the same problem; or my problem can be described exactly with this discussion title 🙂

Here’s my minimal working example:

> \<?php

> require ‘vendor/autoload.php’;

> // Create and configure Slim app  
> $app = new \Slim\App;

> $app-\>get(‘/’, function($request, $response, $args) {  
> $new\_response = $response-\>withJson([‘test’, ‘test2’]);  
> $content\_type = $new\_response-\>getHeader(‘Content-Type’);  
> echo “\n” . $content\_type[0];  
> return $new\_response;  
> });

> $app-\>run();

> $content\_type = $app-\>getContainer()-\>get(‘response’)-\>getHeader(‘Content-Type’);  
> echo “\n” . $content\_type[0];

The output after execution is this:  
`["test","test2"]`  
`application/json;charset=utf-8`  
`text/html; charset=UTF-8`

I’ve even tried adding a `$app->add( function( ServerRequestInterface $request, ResponseInterface $response, callable $next ) { ... } ));` and check the header values before and after the `$next($request, $response);` call.  
The headers are only correct when accessing inside the specific route which was executed. Outside of it, the Content-Type is always the default text/html.

Edit: I’ve installed the framework with the suggested `composer require slim/slim "^3.0"` command. As of today morning, no updates are available, so I presume I’m at the current version: 3.4-0

Edit 2: One more thing worth mentioning: the browser correctly receives the Content-Type JSON header; and replacing the `echo`s with IFs have no impact, the Content-Type is still text/html. (tested it in case somehow the echoing changes the Content-Type back to text/html)

---

<div class="post-metadata">

**Author:** ![JoeBengalen](https://avatars.discourse-cdn.com/v4/letter/j/b5e925/32.png) [@JoeBengalen](https://discourse.slimframework.com/u/JoeBengalen)\
**Post date:** [May 11, 2016, 8:55am UTC](https://discourse.slimframework.com/t/withjson-and-content-type/218/10 "2016-05-11T08:55:24Z")

</div>

@zeroxx1986 You dont have a problem. The behaviour is exacly as expected. Your response in the application has the right content type. Outside the application you get a **new** response object from the container, which has the default content type.

---

<div class="post-metadata">

**Author:** ![zeroxx1986](https://yyz2.discourse-cdn.com/flex030/user_avatar/discourse.slimframework.com/zeroxx1986/32/94_2.png) [@zeroxx1986](https://discourse.slimframework.com/u/zeroxx1986)\
**Post date:** [May 11, 2016, 9:25am UTC](https://discourse.slimframework.com/t/withjson-and-content-type/218/11 "2016-05-11T09:25:19Z")

</div>

Ah, okay, thank you for clarifying.

---

<div class="post-metadata">

**Author:** ![ela1979](https://yyz2.discourse-cdn.com/flex030/user_avatar/discourse.slimframework.com/ela1979/32/661_2.png) [@ela1979](https://discourse.slimframework.com/u/ela1979)\
**Post date:** [May 19, 2016, 4:51am UTC](https://discourse.slimframework.com/t/withjson-and-content-type/218/12 "2016-05-19T04:51:20Z")

</div>

I don’t understand why… But i try once again your suggestion

```
 public function getMembers(Request $req, Response $res, $args)
{
    return parent::get($req, $res, $args, $this->table);
}

```

It’s works now. May be, i make a mistake during the update on the server. It’s works fine now. May be, it’s because i did update Slim to the 3.4.1 version yesterday. I don’t know

Thanks
