【问题标题】:How to serve image from Node Server without Express?如何在没有 Express 的情况下从节点服务器提供图像?
【发布时间】:2017-11-05 09:31:21
【问题描述】:

我正在开发 Node v6.10.2。我正在尝试使用简单的 NodeJS 程序来提供静态元素。当我运行下面提到的代码并转到 http://localhost:3000/ 时,我明白了。

图像未在此处检索。但是当我转到http://localhost:3000/img/logo.jpg 时,我得到了图像。我该如何解决这个问题?

这是服务器代码

var http = require('http');
var fs = require('fs');

function serveStaticFile(res, path, contentType, responseCode) {
    if(!responseCode) responseCode = 200;

    // __dirname will resolve to the directory the executing script resides in.
    // So if your script resides in /home/sites/app.js, __dirname will resolve
    // to /home/sites.

    console.log(__dirname + path);

    fs.readFile(__dirname + path, function(err, data) {
        if(err) {
            res.writeHead(500, { 'Content-Type' : 'text/plain' });
            res.end('500 - Internal Error');
        } 
        else {
            res.writeHead( responseCode, { 'Content-Type' : contentType });
            res.end(data);
        }
    });
}

http.createServer( function (req, res) {
    var path = req.url.replace(/\/?(?:\?.*)?$/, '').toLowerCase();
    switch(path) {
        case '':
            serveStaticFile(res, '/public/home.html', 'text/html');
            break;
        case '/about':
            serveStaticFile(res, '/public/about.html', 'text/html');
            break;
        case '/img/logo.jpg':
            serveStaticFile(res, '/public/img/logo.jpg', 'image/jpeg');
            break;
        default:
            serveStaticFile(res, '/public/404.html', 'text/html', 404);
            break;
    }
}).listen(3000);

console.log('Server started on localhost:3000; press Ctrl-C to terminate...');

这是 html 文件 - home.html

<!DOCTYPE html>
<html>
<head>
    <title>Home</title>
</head>
<body>
    Welcome Home!!!
    <img href="localhost:3000/img/logo.jpg" alt="logo">
</body>
</html>

【问题讨论】:

  • 老兄,这是&lt;img src= 而不是href
  • @evilSnobu 也尝试过。还是一样。
  • 您缺少图片网址前面的http://
  • @PeterReid 谢谢。它奏效了。
  • 作为答案发布在下面,没问题

标签: node.js


【解决方案1】:

您缺少来自img src 的http://。我还要注意,正如@Shashank 指出的那样,您应该使用src 而不是href

把这一切放在一起:

<img src="http://localhost:3000/img/logo.jpg" alt="logo">

【讨论】:

    猜你喜欢
    • 2015-02-26
    • 2014-08-07
    • 2011-02-28
    • 1970-01-01
    • 2021-07-17
    • 1970-01-01
    • 1970-01-01
    • 2017-01-16
    • 1970-01-01
    相关资源
    最近更新 更多