slim framework withHeader json 它不起作用

slim framework withHeader json it does not work

大家好,我正在为 JSON API 使用 slim 框架,所有响应都有效,但在 headers show text / html 上,文档提到了该功能whitHeader:

    $app = new \Slim\App;
    $app->get('/new/', function (Request $request, Response $response){

        $response->getBody()->write(json_encode(['message'=>'ok']));

        $response_h = $response->withHeader('Content-Type', 'application/json; charset=utf-8');

        return json_decode($response_h);
    });
$app->run();

当使用$response_h->getHeaders(); show json header(work) 但是当运行需要另一个 header,我跟踪它替换 header 的位置,并且在 slim / slim / container.php 中,正好在当前函数 registerDefaultServices 中 我替换:

Headers $ headers = new (['Content-Type' => 'text / html; charset = UTF-8']);

Headers $ headers = new (['Content-Type' => 'application / json; charset = utf-8']);

但这不是最好的方法,如何更改headers?

并尝试使用:

$ app-> response () -> header ();
$ app-> response () -> setHeader ();

总的来说return就是响应函数()不存在

使用official documentation for Slim Framework v2:

The HTTP response returned to the HTTP client will have a header. The HTTP header is a list of keys and values that provide metadata about the HTTP response. You can use the Slim application’s response object to set the HTTP response’s header. The response object has a public property headers that is an instance of \Slim\Helper\Set; this provides a simple, standardized interface to manipulate the HTTP response headers.

<?php
$app = new \Slim\Slim();
$app->response->headers->set('Content-Type', 'application/json');

You may also fetch headers from the response object's headers property, too:

<?php
$contentType = $app->response->headers->get('Content-Type');

If a header with the given name does not exist, null is returned. You may specify header names with upper, lower, or mixed case with dashes or underscores. Use the naming convention with which you are most comfortable.

使用official documentation for Slim Framework v3:

An HTTP response typically has a body. Slim provides a PSR 7 Response object with which you can inspect and manipulate the eventual HTTP response’s body.

Just like the PSR 7 Request object, the PSR 7 Response object implements the body as an instance of \Psr\Http\Message\StreamInterface. You can get the HTTP response body StreamInterface instance with the PSR 7 Response object’s getBody() method. The getBody() method is preferable if the outgoing HTTP response length is unknown or too large for available memory.

您的代码应如下所示:

<?php
$app = new \Slim\App();
$app->get('/new/', function(Request $requst, Response $response) {
    $response->getBody()->write(json_encode(['YOUR_ARRAY']));
    $newResponse = $response->withHeader(
        'Content-type',
        'application/json; charset=utf-8'
    );

    return $newResponse;
});

使用 Postman 在我的环境中进行了测试。内容类型已更改。