I am building an http server using node.js and am trying to send an html page for a bad request. Here's my code:

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;
}

As you can see, if the file couldn't be opened I call writeHead() which always ends with \r\n\r\n and then I send an html page.

However, what happens is that I just see the entire response (headers + body) on my browser (chrome if it matters).

有帮助吗?

解决方案

I think you forgot a textual representation of your status code.

HTTP/1.x 200 OK  
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top