Node-static example

为君一笑 提交于 2019-12-23 12:42:27

问题


I've been banging my head against the wall trying to figure out what's wrong with this code. I copied it directly from the node-static github repository example, but it doesn't seem to work. The only modification that I made was to the path of the public files (previously was './public'). In my public folder I have an index.html, but when I hit http://localhost:8080/index.html I get nothing.

var static = require('node-static');

//
// Create a node-static server instance to serve the './public' folder
//
var file = new(static.Server)('C:\Projects\node\public');

require('http').createServer(function (request, response) {
    request.addListener('end', function () {
        //
        // Serve files!
        //
        file.serve(request, response);
    });
}).listen(8080);

If it matters, I'm running Node.js on Windows 7 64 bit.

Edit:

I threw in some console.log statements and it makes it into the server handler, but not into the listener handler. Could this have something to do with the 'end' event?


回答1:


I removed the request.addListener('end', ...) function:

require('http').createServer(function (request, response) {

    //
    // Serve files!
    //
    file.serve(request, response);

}).listen(8080);

Now it works fine.




回答2:


I think you have a windows path problem. I cannot verify it on my side but I can give you 2 options:

1) escape your backslashes:

'C:\\Projects\\node\\public'

2) use path.join

var path = require("path");
var file = new(static.Server)(path.join(__dirname, "public"));

__dirname is the path of the current file.




回答3:


In addition, if you want to serve error page also

let static = require('node-static');

let fileServer = new static.Server('C:\Projects\node\public');

require('http').createServer(function (request, response) {

    fileServer.serve(request, response, function (exception) {
        if (exception && (exception.status === 404)) {
            fileServer.serveFile('/404.html', 404, {}, request, response);
        }
    });

}).listen(8080);

file 404.html should exist



来源:https://stackoverflow.com/questions/15419882/node-static-example

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!