简体   繁体   中英

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

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.

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

I would recomend you to use node express module http://expressjs.com/ which will allow you to write custom template renderer as well as static pages including css and js image files

simply install express using

npm -g install express

Following up on @Dickens answer here is the basic express app that handles your form and all static files in ./public/

//dependencies
var http = require ('http');
var express = require('express'); // npm install --save express
var app = express();

app.use(express.static(__dirname+'/public'));

app.post('/formHandler', function(req, res){
  res.status(200).send('rrr');
})
var server = http.createServer(app);

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


// Test with:
// curl -vX POST http://localhost:4000/formHandler
// curl -vX GET http://localhost:4000/index.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM