【问题标题】:sending 404 status but browser displays 500 error at client side发送 404 状态但浏览器在客户端显示 500 错误
【发布时间】:2013-10-07 17:13:14
【问题描述】:

我正在尝试根据 IF 条件发送 http 404 状态代码。但是,在客户端我看到 http 500 错误。 在我的 apach2 错误日志中,我看到了格式错误的标头。 多次查看我的代码后,我无法弄清楚出了什么问题! 谁能建议我如何向客户发送 404 消息?

下面是我的 perl 代码:

#!/usr/bin/perl

use CGI qw(:standard);
use strict;
use warnings;
use Carp;
use File::Copy qw( copy );
use File::Spec::Functions qw( catfile );
use POSIX qw(strftime);
use Time::Local;
use HTTP::Status qw(:constants :is status_message);
use Digest::MD5 qw(md5 md5_hex md5_base64);
use File::Basename;
use URI;



my $extfile = '/home/suresh/clientrequest.txt';
open(FH, ">>$extfile") or die "Cannot open file";
my $query = CGI->new;
my $stcode = status_message(200);
my $uri =$ENV{'REQUEST_URI'};
my $rdate =strftime("%a, %d %b %Y %H:%M:%S %Z", localtime());
print FH "Got Following Headers:\n";
print FH $ENV{'REQUEST_URI'}, "\n";
my $dir  = '/home/suresh/Assets/';
my $nffFile = fileparse ("$uri", qr/\.[^.]*/);
my $fullFname = $nffFile . ".nff";
my $path = catfile($dir, $fullFname);
print FH "fullname:", $fullFname, "\n";

#Search requested asset files
opendir(DIR, $dir);
my @files = readdir(DIR);
if (grep($_=~/$fullFname/,@files)){
print FH "Found the file: ", $fullFname, "\n";
open my $fh, '<:raw', $path;
print "$ENV{SERVER_PROTOCOL} 200 $stcode";
print $query->header(
        -'Date'=> $rdate,
        -'Content-Type'=>'application/octet-stream',
        -'Connection'=>'Keep-Alive',
        -'attachment'=>$path,
    );
binmode STDOUT, ':raw';

 copy $fh => \*STDOUT;
    close $fh
        or die "Cannot close '$path': $!";

}else {
        $stcode = status_message(404);
        print "$ENV{'SERVER_PROTOCOL'} 404 $stcode\n";
        print $query->header(
        -'Server'=>$ENV{'SERVER_SOFTWARE'},
        -'Content-type'=>'text/plain',
        );
        }
closedir(DIR);

【问题讨论】:

  • 为什么要投票?如果您已经投票,请说明理由。

标签: perl apache2 cgi http-status-codes


【解决方案1】:

您应该先打印标题,然后再打印其他内容。否则,浏览器将不知道如何处理您发送给它的内容。而不是这个:

print "$ENV{SERVER_PROTOCOL} 200 $stcode";
print $query->header( ... );

这样做:

print $query->header( ... );
print "$ENV{SERVER_PROTOCOL} 200 $stcode";

此外,您可以使用 CGI.pm 指定 HTTP 状态代码:

print $query->header( -status => '404 Not Found' );

调试 CGI 应用程序的小技巧:更改

use Carp;

use CGI::Carp qw(fatalsToBrowser);

这将直接在浏览器中显示致命错误,因此您不必在网络服务器日志中四处寻找。但是,请不要在生产代码中启用fatalsToBrowser 选项,因为它可能会向攻击者泄露应用程序的内部工作原理。

【讨论】:

  • 谢谢!!行 print $query->header( -status => '404 Not Found' );成功了,它奏效了!! .有趣的是..在标题之前保留的状态行仅适用于状态 200,不适用于其他状态代码!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-17
  • 1970-01-01
  • 2021-03-01
  • 1970-01-01
  • 2020-07-04
  • 1970-01-01
相关资源
最近更新 更多