【问题标题】:Cannot load html image using localhost node.js/express.js server无法使用 localhost node.js/express.js 服务器加载 html 图像
【发布时间】:2017-06-25 13:47:19
【问题描述】:

我正在使用以下 node.js/express.js 服务器,

index.js:

const express = require('express');
const path = require('path');

const app = express();

app.get('/', function(req, res) {
    res.sendFile(path.join(__dirname + '/index.html'));
});

app.listen(8000, function () {
    console.log('Listening on port: 8000!');
});

以及下面的html文件,

index.html:

<!doctype html>
<html> 
<head> 
    <title>Will Alley</title>
</head>
<body>
    <style type="text/css">
        img {
            width: 100%;
            height: 100%;
        }
    </style>
    <h2 id="myName">Will Alley</h2>
    <img src="./DSC_1546_700_464.jpg" alt="an image.">
</body>
</html>

我所有的文件(index.js、index.html、DSC_1546_700_464.jpg)都在同一个目录中。

当我启动服务器并导航到“localhost:8000”时,显示的只是标题和图像替代文本。

非常感谢任何帮助。

【问题讨论】:

    标签: javascript html css node.js express


    【解决方案1】:

    快递中只有一条路线,即“/”路线。
    以下是两个补充,一个通过添加 app.use(express.static(__dirname)) 来回答您的特定问题,这很危险。更安全的方法是使用 app.use('/images',express.static(__dirname+'/images')) 之类的东西来服务于您放置可服务内容的某些子目录。

    const express = require('express');
    const path = require('path');
    
    const app = express();
    
    app.get('/', function(req, res) {
    res.sendFile(path.join(__dirname + '/index.html'));
    });
    // Static route for files in the current directory...
    // Note that this serves all files relative to the given
    // path, even ones you probably don't want.
    app.use(express.static(__dirname));
    
    // Note: you should really put these files in a subdirectory
    // And use static like this:
    app.use('/images', express.static(__dirname +'/images'));    
    
    app.listen(8000, function () {
        console.log('Listening on port: 8000!');
    });
    

    【讨论】:

    • 我添加了一个图像子目录并按照您推荐的方式使用了静态,但问题仍然存在。 (我还更新了我的 html 中的文件路径)
    • 忽略,我在修改中有一个类型,你的回答有效,谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-29
    • 1970-01-01
    • 2017-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多