0

我正在http使用 node.js 构建服务器,并尝试发送html错误请求的页面。这是我的代码:

function respond(request, socket) {
    console.log("Request for " + request["url"] + ".");
    fs.readFile(request["url"], request["encoding"], function(error, file) {
        if(error) {
            console.log(error);
            writeHead(socket,request["version"],404,"text/html",null);
            socket.write(notFound(request["url"]));
            socket.end();
        } else {
            fs.stat(request["url"],function (err,stats) {
                writeHead(socket,request,200,stats)
                socket.write(file, request["encoding"]);
                socket.end();
            });
        }
    });
}

function notFound(url) {
return "<html> \
    <head> \
    <title>404 Not Found</title> \
    </head> \
    <body> \
    <h1>Not Found</h1> \
    <p>The requested URL " + url + " was not found on this server.</p> \
    <hr> \
    <address>EX4 Server</address> \
    </body> \
    </html>"
}

function writeHead(socket, request, code, stats) {
    socket.write(request["version"] + " " + code + " " + "\r\n");
    socket.write("Date: " + getDate() + "\r\n");
    if (stats != null) {
        socket.write("Content-Length: " + stats.size + "\r\n");
        socket.write("Last-Modified: " + stats.mtime + "\r\n");
    }
    socket.write("Server: EX4" + "\r\n");
    socket.write("Content-Type: " + request["contentType"] + "\r\n");
    socket.write("\r\n");
    return;
}

如您所见,如果文件无法打开,我会调用writeHead()它总是以结尾,\r\n\r\n然后发送一个 html 页面。

但是,发生的情况是我只在浏览器上看到了整个响应(标题 + 正文)(如果重要,则为 chrome)。

4

1 回答 1

1

我认为您忘记了状态代码的文本表示。

HTTP/1.x 200 OK  
于 2012-12-10T21:02:51.123 回答