修身附加标题

I want to append token inside header in slim when $token not empty. I append new header with function withAddedHeader()

from slim documentation

This is my code:

$res = $this->response->withHeader('Content-type', 'application/json');
if ($token !== null) {
    $res->withAddedHeader('token', $token);
}

But still not working, new header not appended.

with**() method of Response class returns clone of current Response instance to maintain immutability.

To add header properly, you need to return newly cloned response before exiting route handler.

$res = $this->response->withHeader('Content-type', 'application/json');

if ($token !== null) {
    return $res->withAddedHeader('token', $token);
}

return $res;