简体   繁体   English

根据网址提供HTML页面

[英]Serve a html page based on a url

im trying to do something with node, basicly i created the server, and now based on the url i want to get the html page, i created some html pages on my project, i need to return the html page. 我试图对节点做一些事情,基本上我创建了服务器,现在基于URL我想获取html页面,我在项目中创建了一些html页面,我需要返回html页面。

i did this 我做到了

var http = require("http");
var url = require("url");
var fs = require("fs");

var server = http.createServer(function(request,response){

    var result = url.parse(request.url,true);
    var path = result.pathname;

    fs.readFile(path,function(err,data){
        if(err){
            return console.log("fail");
        }
        console.log(data);
    })


    response.writeHead(200,{'Content-Type': 'text/html'});
    console.log(path);

    response.end();
})

server.listen(3000);
console.log("servidor em execução");

it kinda fails, the fs.readfile enters in the error, i dont know very well what i am doing wrong and how to fix this, can you guys give me a little help, thanks a lot 它有点失败,fs.readfile输入错误,我不太清楚我在做什么错以及如何解决这个问题,你们能给我一点帮助,非常感谢

You should try with dirname 您应该尝试使用dirname

if(requestUrl.endsWith('index.html'))
{
    data=fs.readFileSync(__dirname + '/../html/index.html', 'utf-8')
                           |           |    |
                           |           |    v
                           |           v   html folder and file
                           v         cd..(move 1 level up)
                           the directory of current js file(your main js file)
}

used sync version for simplicity of course you use async version as it is nodejs friendly and performance aware. 为了简单起见,使用了同步版本。当然,您使用的是异步版本,因为它对Node.js友好且性能敏感。 You shouldn't put requests from clients directly into fs or database commands. 您不应将来自客户端的请求直接放入fs或数据库命令中。

result.pathname would always give you path without the domain eg if requested url is ' http://localhost:1337/mycustomFolder/myfile.html ' then pathname would give you '/mycustomFolder/myfile.html' and fs.readfile(path... would always append this with the root directory mapped to domain directory which in my case because it's C:\\ because i'm running node.js on my local through a command prompt. So final path became C:\\mycustomFolder\\myfile.html result.pathname将始终为您提供没有域的路径,例如,如果请求的URL为“ http:// localhost:1337 / mycustomFolder / myfile.html ”,则pathname名将为您提供“ /mycustomFolder/myfile.html”和fs.readfile(path...总是将根目录附加到映射到域目录的根目录,在我的情况下,因为它是C:\\,因为我通过命令提示符在本地运行node.js,所以最终路径变为C:\\ mycustomFolder \\ myfile .html

you can update this relative path with any directory you want if current directory is not the one you are looking for and make an absolute path before passing it to readfile function, see the example below. 如果当前目录不是您要查找的目录,则可以使用所需的任何目录更新此相对路径,并在将其传递给readfile函数之前创建一个绝对路径,请参见下面的示例。 you can also use ..\\ any number of time if you want to point to any parent directory 如果您想指向任何父目录,也可以使用.. \\任意多次

console.log('Starting server');
var http = require("http");
var url = require("url");
var fs = require("fs");

http.createServer(function (req, res){
    var result = url.parse(req.url,true);
    var path = result.pathname;
    path = 'C:\\Projects' + path;
console.log(path);
    fs.readFile(path,function(err,data){
        if(err){
            return console.log(err);
        }
        else
        console.log(data);
    })


    res.writeHead(200,{'Content-Type': 'text/html'});
    console.log(path);

    res.end();
}).listen(1337, '127.0.0.1');

console.log('Server started at port 1337');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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