Javascript httpdispatcher中的setStatic函数
我正在node.js中构建一个服务器,但无法理解我在网上得到的这个示例中httpdispatcher中setStatic的功能Javascript httpdispatcher中的setStatic函数,javascript,node.js,Javascript,Node.js,我正在node.js中构建一个服务器,但无法理解我在网上得到的这个示例中httpdispatcher中setStatic的功能 var http = require('http'); var dispatcher = require('httpdispatcher'); //Lets define a port we want to listen to const PORT=8080;
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);
});
但是当我运行这个文件并键入url时,我在终端中得到了以下内容[TypeError:path.join的参数必须是字符串],浏览器上没有显示任何内容,但在资源文件夹下有一个dwnl.png
添加以下行
dispatcher.setStaticDirname(__dirname);
以前
dispatcher.setStatic('resources');
并尝试使用请参阅此答案,其中解释了在使用httpdispatcher之前必须使用以下内容进行实例化:
var httpdispatcher = require('httpdispatcher');
var dispatcher = new httpdispatcher();
否则,您将得到运行时类型错误,因为调度程序不存在 尝试在终端上不显示错误,但浏览器上只有一个空白的白色屏幕。您可以将图像附加到此处吗?包含app.js文件的目录有一个名为resources的子目录,其中图像位于其中。在这种情况下,必须在浏览器上可见。你也可以试着表达。服务于请求是很好的。同时,我正在检查您的代码。不幸的是,它现在正在显示…感谢您的帮助…请让我知道完整的目录结构,一旦您在mycodeI中发现错误,请更新答案,请尝试。如果答案对你有效,就接受它。谢谢