【问题标题】:Slim framework does not send http headers when http status is not 200当 http 状态不是 200 时,Slim 框架不发送 http 标头
【发布时间】:2021-12-09 09:14:06
【问题描述】:

我正在使用 PHP Slim 框架 v4。我尝试发送 HTTP 标头和 HTTP 错误代码。使用 HTTP 状态 200 它工作正常。指定 304 时,响应错误码没问题,但这种情况下缺少标头。

return $response->withHeader('Content-Type', 'text/plain')
    ->withHeader('X-Error-Message', $message)
    ->withHeader("Access-Control-Allow-Origin", $_SERVER['HTTP_ORIGIN'])
    ->withStatus(200);

这可行,但如下所述的代码不提交标头

return $response->withHeader('Content-Type', 'text/plain')
    ->withHeader('X-Error-Message', $message)
    ->withHeader("Access-Control-Allow-Origin", $_SERVER['HTTP_ORIGIN'])
    ->withStatus(304);

任何想法为什么这不起作用?

如您所见,我需要一个 CORS 标头以避免浏览器抛出错误。

【问题讨论】:

    标签: php http error-handling http-headers slim


    【解决方案1】:

    我猜你在 PHP 中收到了这个内部警告:

    Warning: Undefined array key "HTTP_ORIGIN" 
    

    此警告将在 Slim $response 被处理之前由 PHP 发送。

    请注意HTTP_ORIGIN 标头并不总是存在,并且依赖此密钥不是一个好习惯。相反,最好检查域并在有效时发送*

    这会阻止这个警告试试这个:

    $httpOrigin = $request->getServerParams()['HTTP_ORIGIN'] ?? '';
    if($httpOrigin) {
        $response = $response->withHeader('Access-Control-Allow-Origin', $httpOrigin);
    }
    
    return  $response->withHeader('Content-Type', 'text/plain')
        ->withHeader('X-Error-Message', $message)
        ->withStatus(403);
    

    【讨论】:

      【解决方案2】:

      报告的问题不是由 slim 框架引起的。我们的托管服务提供商使用 apache 作为 Web 服务器。 Apache 导致了这种行为。

      更多详情请见https://bz.apache.org/bugzilla/show_bug.cgi?id=61820

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-11-27
        • 1970-01-01
        • 2014-09-20
        • 2016-11-30
        • 2018-05-28
        • 1970-01-01
        • 1970-01-01
        • 2016-10-24
        相关资源
        最近更新 更多