如何在没有Express的情况下从Node Server提供图像?

时间:2017-06-04 13:59:04

标签: node.js

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

enter image description here

此处无法检索图像。但是当我去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>

1 个答案:

答案 0 :(得分:2)

您错过了http:// src中的img。我还要注意,@Shashank指出你应该使用src而不是href

把这一切放在一起:

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