【问题标题】:adding a response header to 302 response using perl使用 perl 将响应标头添加到 302 响应
【发布时间】:2012-04-15 12:10:47
【问题描述】:

我正在尝试编写一个 perl 页面,该页面将 http 302 响应返回到不同的位置,并将自定义标头添加到该响应中。 所以我想要的http响应应该是这样的:

HTTP/1.1 302 Moved
Date: Sun, 15 Apr 2012 10:59:02 GMT
Server: Apache
Location: http://www.google.com
Content-Length: 396
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Content-Type: text/html; charset=iso-8859-1
CUSTOM_HEADER: CUSTOM_VALUE

我尝试使用 CGI:

#!/bin/perl

use strict;
use APR::Request::Apache2;
my $r = shift;
$r->content_type('text/html; charset=utf-8');
$r->headers_out()->add("CUSTOM_HEADER", "CUSTOM_VALUE");
$r->headers_out()->add("Location", "http://www.google.com");
$r->status(302);

我确实收到了对 google 的 302 响应,但没有 CUSTOM_HEADER。一旦我通过$r->status(200); 将状态更改为 200,我确实得到了 CUSTOM_HEADER。 那么这种行为是怎么回事?如何将我的标头添加到 302 响应中?

【问题讨论】:

    标签: perl http http-headers http-status-code-302


    【解决方案1】:

    使用$r->err_headers_out->set$r->err_headers_out->add

    my $r = shift;
    
    $r->content_type('text/html; charset=utf-8');
    $r->err_headers_out->set(Location => "http://www.google.com");
    $r->status(302);
    

    【讨论】:

    • 感谢您的帮助。顺便问一下,为什么 302 被认为是错误响应?
    • @Oded - 好问题。我明白你的意思了 :) 状态码 1xx 是信息性的,2xx 成功,3xx 重定向,4xx 客户端错误和 5xx 服务器错误。所以 302 不是成功,不是错误。那么它是什么?在这种情况下,对于此模块和功能,它是错误的。不要问为什么:)
    【解决方案2】:

    您应该使用err_headers_out()。即使出现错误和重定向,这些也会被打印出来。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-31
      • 1970-01-01
      • 2015-06-10
      • 2021-02-17
      • 2016-05-15
      • 2019-09-05
      相关资源
      最近更新 更多