我在node.js中构建服务器,但在网络上的此示例中无法在httpdispatcher中破坏setStatic的功能。

            var http = require('http');
            var dispatcher = require('httpdispatcher');
            //Lets define a port we want to listen to
            const PORT=8080;

            //We need a function which handles requests and send response
            function handleRequest(request, response){
                //response.end('It Works(Refereshed)!! Path Hit: ' + request.url);
                try{
                    console.log(request.url);
                    dispatcher.dispatch(request,response);

                }catch(err){console.log(err);}

            }

            //set all js/html/css as static during response
            dispatcher.setStatic('resources');

            dispatcher.onGet("/page1",function(req,res){
                res.writeHead(200,{'Content-Type':'text/plain'});
                res.end("Page one");
            });

            dispatcher.onPost("/page2",function(req,res){
                res.writeHead(200,{'Content-Type':'text/plain'});
                res.end("Get Post Data");
            });


            //Create a server
            var server = http.createServer(handleRequest);

            //Lets start our server
            server.listen(PORT, function(){
                //Callback triggered when server is successfully listening. Hurray!
                console.log("Server listening on: http://localhost:%s", PORT);
            });


但是,当我运行此文件并键入http://localhost:8080/resources/dwnl.png之类的url时,我在终端中得到以下内容[TypeError:path.join的参数必须为字符串],浏览器上未显示任何内容,但是我在资源文件夹下有dwnl.png

javascript - httpdispatcher中的setStatic函数-LMLPHP

最佳答案

添加以下行

dispatcher.setStaticDirname(__dirname);


之前

dispatcher.setStatic('resources');


并尝试使用http://localhost:8080/resources/dwnl.png

09-18 07:30