简体   繁体   English

如何设置nodejs服务器,通过检查URL为客户端提供正确的文件?

[英]How do I set up a nodejs server that gives the client the correct file by checking the url?

I am trying to write a node js server that gives back whatever the user requested, if the resource is in the file system. 我正在尝试编写节点js服务器,如果资源在文件系统中,则返回用户请求的任何内容。

For example, if the request URL were /index.html , it would try to find a file called 'index.html' in the root directory and respond with a stream to that file. 例如,如果请求URL是/index.html ,它将尝试在根目录中找到名为“index.html”的文件,并使用该文件的流进行响应。 If the request were /myscript.js , it would do the same, finding a file called myscript.js and piping that to the response. 如果请求是/myscript.js ,它会做同样的事情,找到一个名为myscript.js的文件并将其传递给响应。

Here is what I have so far: 这是我到目前为止:

var http = require("http");
var fs = require("fs");
var port = process.env.PORT || 3000;
http.createServer(function (request, response) {
    if (request.method == "GET") {
        console.log(request.url);
        if (request.url == "/") { // if the url is "/", respond with the home page
            response.writeHead(200, {"Content-Type": "text/html"});
            fs.createReadStream("index.html").pipe(response);
        } else if (fs.existsSync("." + request.url)) {
            response.writeHead(200/*, {"Content-Type": request.headers['content-type']}*/);
            fs.createReadStream("." + request.url).pipe(response);
        } else {
            response.writeHead(404, {"Content-Type": "text/plain"});
            response.end("404 Not Found");
        }
    } else {
        response.writeHead(404, {"Content-Type": "text/plain"});
        response.end("404 Not Found");
    }
}).listen(port);

// Console will print the message
console.log('Server running at http://127.0.0.1:' + port +'/');

There are a few things that I don't like about this code: 关于这段代码我有一些不喜欢的事情:

  • Apparently fs thinks that whenever the path starts with / , the file does not exist, so I must add a . 显然fs认为每当路径以/开头时,文件就不存在,所以我必须添加一个. before the file path. 在文件路径之前。 See line 10 and 12. Will this always work? 见第10和第12行。这总是有效吗? I feel like this is a really bad trick to work around the problem. 我觉得这是解决这个问题的一个非常糟糕的伎俩。
  • I don't know the content type of the requested file (line 11). 我不知道所请求文件的内容类型(第11行)。 I searched online and found a lot of ways to do this with other modules that I have to install using npm. 我在网上搜索并发现很多方法可以使用我必须使用npm安装的其他模块。 Is there something in node that will figure out the content type? 节点中是否有东西可以找出内容类型?

Addressing your two bullet points: 解决你的两个要点:

  • It makes sense that you would need a . 你需要一个有意义的. when using fs because fs will look at the root directory of your system otherwise. 使用fs因为fs会查看系统的根目录。 Remember, the system root is different than your server root. 请记住,系统根目录与服务器根目录不同。
  • One idea is to use path.extname and then a switch statement to set the content type like so. 一个想法是使用path.extname然后使用switch语句来设置内容类型。

The code below is taken from an blog post I wrote on how to set up a simple static server using Node without Express: 下面的代码来自我写的关于如何使用Node而不是Express设置简单静态服务器的博客文章

let filePath = `.${request.url}`; // ./path/to/file.ext
let ext = path.extname(filePath); // .ext
let contentType = 'application/octet-stream'; // default content type

if(ext === '') {

    filePath = './index.html'; // serve index.html
    ext = '.html';
}

switch (ext) {

    case '.html':
        contentType = 'text/html';
        break;

    case '.css':
        contentType = 'text/css';
        break;

    case 'js':
        contentType = 'text/javascript';
}

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

相关问题 我如何在服务器响应中设置 cookie 和 json 并重定向到客户端 url/PassportJS NodeJS - How i can set cookie and json in server response and redirect to client url/ PassportJS NodeJS 如何更改URL Websocket NodeJ(服务器/客户端) - How to change URL Websocket NodeJs (server/client) 如何在 Javascript 中正确设置 Cassandra 客户端? - How do I properly set up the Cassandra client in Javascript? 如何在Web服务器上设置gzip压缩? - How do I set up gzip compression on a web server? 如何在Node.js中设置Web缓存代理服务器以减少Internet使用 - How can I set up a web cache-proxy server in nodejs to reduce internet usage 我如何使用Node.js在服务器上接收与客户端发布数据格式相同的发布数据? - How do i receive post data at server same as client post data format using nodejs? 如何将变量从客户端 NodeJS 传递到服务器端? - How do I pass a variable from client side NodeJS to server side? 如何将数据从客户端表单输入传输到服务器端Nodejs脚本? - How do I transfer data from a client-side form input to a server-side Nodejs script? 如何在Node.js中将用户的电话号码设置为密码恢复选项 - How do I set up a user's phone number as a password recovery option in Nodejs 如何继续检查javascript中的值是否正确? - How do I continue checking whether a value is correct in javascript?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM