Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
150 views
in Technique[技术] by (71.8m points)

ajax - nodejs cannot serve static files - downloads them

I am playing around with nodejs, creating a simple server, also handles some ajax. When I go to localhost:4000 the page does not render, instead an empty file is automatically downloaded. It is named "download file", zero byte and no extension.

I think my client and my server are really simple. Sorry for the generic question but I fail to understand why this is happening.

Thanks in advance

Client - a simple form and a XHR that sends json-type data

<html>
    <head>        <title>Chatrooms</title>    </head>    
    <body>
<form id="fruitform" method="post" action="/">
<div class="table">
<div class="row">
<div class="cell label">Bananas:</div>
<div class="cell"><input name="bananas" value="2"/></div>
</div>
<div class="row">
<div class="cell label">Apples:</div>
<div class="cell"><input name="apples" value="5"/></div>
</div>
<div class="row">
<div class="cell label">Cherries:</div>
<div class="cell"><input name="cherries" value="20"/></div>
</div>
<div class="row">
<div class="cell label">Total:</div>
<div id="results" class="cell">0 items</div>
</div>
</div>
<button id="submit" type="button">Submit Form</button>
</form>
<div id="results"></div>
<div id="de"></div>

 </body>
</html>

<script type="text/javascript">

document.getElementById("submit").onclick = handleButtonPress;

function handleButtonPress(e) {
    e.preventDefault();
    var formData = "";
    //gather all input values in a json type string
    var inputElements = document.getElementsByTagName("input");
    for (var i = 0; i < inputElements.length; i++) {
        formData += inputElements[i].name + "=" + inputElements[i].value + "&";     
    }
    formData = formData.slice(0, -1);
    var hr = new XMLHttpRequest();
    hr.open("POST", "/formHandler", true);
    hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    hr.onreadystatechange = function() {
        if(hr.readyState == 4 && hr.status == 200) {
            document.getElementById("results").innerHTML = hr.responseText;
        }
    }
    hr.send(formData);
}
</script>

Server

//dependencies
var http = require ('http');
var fs = require ('fs');
var path = require ('path');
var mime = require ('mime');
var qs = require('querystring');


//this is the http server
var server = http.createServer(function (request, response){
    var filePath = false;
    if (request.url == '/'){
        filePath='public/index.html';//default static file
    }

    if (request.url == '/formHandler'){//handle XHR
            if (request.method=="POST"){
                var rrr="rrr";
                response.writeHead(200,{"content-type":"text/plain"});
                response.write(rrr);
                response.end(rrr);
            }
    }

    else{
        filePath='public'+request.url;//set relative file path
    }
    var absPath = './'+filePath;
    serveStatic(request, response, cache, absPath);//serve the static file

});

server.listen(4000, function(){
    console.log("Chatrooms server on port 4000");
    }
);

//read static files 
function serveStatic(request, response,cache, absPath){
    fs.readFile(absPath, function(err, data){
            sendFile(request, response, absPath, data);

    })
}

//serve file data
function sendFile(request, response, filePath, fileContents){
    response.writeHead(
        200,{"content-type":mime.lookup(path.basename(filePath))}
    );
    response.end(fileContents);     
}

UPDATE If I remove the following part from the server, it works fine. Still cannot understand what is going on

    if (request.url == '/formHandler'){
        console.log("inside ajax if");
            console.log("inside formPro");
            if (request.method=="POST"){
                console.log("inside second ajax if");
                var rrr="rrr";
                response.writeHead(200,{"content-type":"text/plain"});
                response.write(rrr);
                response.end(rrr);
                console.log("finished sending rrr");
            }
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Most likely fs.readFile is returning an error, which you are ignoring.

When serving static files you should not read the whole thing into memory like this. The whole point of Node.JS is to keep I/O freely flowing.

Use fs.createReadStream(filePath).pipe(response) instead, although you will need to add an error listener, or run within a domain.


UPDATE

Bugs abound - you don't return from any cases and just carry through to the next one.

i.e. You can end up calling both request.end() and serveStatic.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...