节点JS没有提供静态图像 [英] Node JS not serving the static image

查看:120
本文介绍了节点JS没有提供静态图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经添加了用于在我的节点服务器上提供图像的代码,但在连接到节点时似乎不在HTML中提供图像。我也有正确的服务外部CSS和JS。这是我在Node中代码的片段(见下文)。

  var server = http.createServer(function(req,res){
var pathname = url.parse(req.url).pathname;
var ext = path.extname(pathname);
var handler = handlers [req.url];
if(ext){
if if(ext ===.css){
res.writeHead(200,{Content-Type:text / css});
}
else if (ext ===.js){
res.writeHead(200,{Content-Type:text / javascript});
}
else if(ext = ==.jpg){
res.writeHead(200,{Content-Type:image / jpg});
}
res.write(fs.readFileSync( __dirname + pathname,utf8));
res.end();
}
else if(handler){
handler(req,res);
}
else {
res.writeHead(404,{Content-type:text / plain});
res.end();
}
});
server.listen(80);


解决方案

我见过很多像这样的问题当有人试图实现他们自己的静态文件服务器而不是使用Express或其他可行的工具时,堆栈溢出,并且无法工作。如果你可以实现你自己的静态文件服务器,那就去做吧。如果你不能,那么它应该是一个标志,也许这不是一个好主意。 更新:请参阅下文,了解不使用Express的解决方案。 b

只要看看你的代码,我已经看到了几个严重的问题,包括: 你的代码是不安全 - 它允许任何人在您的系统上获取任何文件。 您的代码阻止 - 只要您获得任何并发连接,它就会立即停止。 您的代码不适用于二进制文件 - 仅适用于文本文件,并且只适用于使用UTF-8编码的文件。 您的代码不适用于大写文件名 .jpeg 扩展名等。 您的代码无法正确投放 HTML 文件当您的代码崩溃时,如果文件不存在而不是使用正确的代码进行响应 $ b



解决方案



A回答这样的问题的任何人有两种选择:或者花费大量的精力和时间来解决上述所有问题(这很少发生,因为这不是一项简单的任务,这就是为什么你看到的只是提到的一个问题或其中两个问题,而不是答案),您可以解释如何正确完成任务,而不是将无数修复添加到首先不是好主意的事情中。



前面已经说过,以安全和高性能的方式实现您的目标的方法是将静态文件(HTML,CSS,图像等)放入目录中,例如称为 html 并使用 Express (或其他一些框架,请参阅如下所示:

  var path = require('path'); 
var express = require('express');
var app = express();

var htmlPath = path.join(__ dirname,'html');

app.use(express.static(htmlPath));

var server = app.listen(80,function(){
console.log('listen on port',server.address()。port);
}) ;

请参阅完整示例以及有关GitHub的解释:





我把这个例子放在GitHub上,因为Stack Overflow有很多问题与人们在Node中提供静态文件时遇到的问题有关。它是开源的,您可以根据自己的需要进行调整并在代码中使用。



有关Express的更多信息,请参阅:



其他选项



您可以用来提供静态文件的其他框架包括:



没有框架



如果您仍然认为您不想使用一个能够纠正工作的高层框架tly,你想推出你自己的解决方案,也许出于教育目的,然后看到这个答案:


  • 如何使用nodejs提供图片



  • 它解释了如何使用静态图片:


    1. express.static express 内置中间件,就像在这个答案中一样)

    2. express ( express 但没有 express.static ))

    3. connect (比 express 低一级)
    4. $ $ b $ li code> http
      (使用Node的 http 模块)
    5. net (甚至不使用 http 模块)

    所有发布的示例都经过测试,可用于Node 4,5,6和7版本。



    其他相关答案:



    $ b加载partials失败$ b

    I have already added the codes for serving an image on my node server but it seems to not serve images in the HTML when connecting to Node. I have also external CSS and JS that are being served correctly. Here is the fragment of my code in Node (See below). Thank you in advance!

    var server = http.createServer(function(req, res) {
        var pathname = url.parse(req.url).pathname;
        var ext = path.extname(pathname);
        var handler = handlers[req.url];
        if(ext) {
            if(ext === ".css"){
                res.writeHead(200, { "Content-Type" : "text/css" });
            }
            else if(ext === ".js") {
                res.writeHead(200, { "Content-Type" : "text/javascript" });
            }
            else if(ext === ".jpg") {
                res.writeHead(200, { "Content-Type" : "image/jpg" });
            }
            res.write(fs.readFileSync(__dirname + pathname, "utf8"));
            res.end();
        }
        else if(handler) {
            handler(req, res);
        }
        else {
            res.writeHead(404, { "Content-type" : "text/plain" });
            res.end();
        }
    });
    server.listen(80);
    

    解决方案

    I've seen a lot of questions like this on Stack Overflow when someone tries to implement their own static file server instead of using Express or something that works, and fails to make it work. If you can implement your own static file server then do it. If you can't, then it should be a sign that maybe it's not a good idea. Update: See below for solutions without Express.

    Problems

    Just by glancing at your code code I already see several serious problems with it, including:

    1. Your code is insecure - it allows anyone to get any file on your system.

    2. Your code is blocking - it will grind to a halt as soon as you get any concurrent connections.

    3. Your code doesn't work for binary files - only for text files, and only those with UTF-8 encoding

    4. Your code doesn't work for uppercase filenames, .jpeg extension etc.

    5. Your code doesn't serve HTML files correctly

    6. Your code crashes when files don't exist instead of responding with proper code

    Solution

    Anyone who answers a question like this has two options: either put a lot of effort and time into fixing every one of the problems mentioned above (which rarely happens because it is not a trivial task and that's why all you see are comments mentioning one or two of those problems instead of answers) or you can explain how the task should be done properly instead of adding countless fixes to something that was not a good idea in the first place.

    That having been said, what you can do to achieve your goal here in a secure and performant way is to put your static files (HTML, CSS, images etc.) into a directory, e.g. called html and use Express (or some other frameworks, see below) with a simple code like this:

    var path = require('path');
    var express = require('express');
    var app = express();
    
    var htmlPath = path.join(__dirname, 'html');
    
    app.use(express.static(htmlPath));
    
    var server = app.listen(80, function () {
        console.log('listening on port', server.address().port);
    });
    

    See the full example with explanation on GitHub:

    I put this example on GitHub because there are a lot of questions on Stack Overflow related to problems that people have with serving static files in Node. It's open-source, you can adapt it to your own needs and use in your code.

    For more info on Express, see:

    Other options

    Other frameworks that you can use to serve static files include:

    Without a framework

    If you still think that you don't want to use a high-level framework that does the job correctly and you want to roll your own solution, maybe for educational purposes, then see this answer:

    It explains how to serve static images with:

    1. express.static (express built-in middleware, like in this answer)
    2. express (express but without express.static)
    3. connect (one level below than express)
    4. http (using Node's http module)
    5. net (not even using http module)

    All of the examples posted are tested and work on Node versions 4, 5, 6 and 7.

    Other related answers:

    这篇关于节点JS没有提供静态图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆