【问题标题】:Displaying images from html in Node在 Node 中显示来自 html 的图像
【发布时间】:2019-12-10 01:35:31
【问题描述】:

我试图让 Node 显示一个 HTML 文件(使用 fs、http 和 express),但该文件中的图像显示为断开的链接符号。

我试过写下面的代码,我有多次修改,但都没有成功。

var http = require('http');
var fs = require('fs');
var express = require('express');
var path = require('path');
var dt = require('./modules/myFirstModule');

var port = 3000;

var app = express();

app.use(express.static(path.join(__dirname + 'public')));
console.log(__dirname);
app.use('/images', express.static(path.join(__dirname + 'public' + 'images')));

http.createServer(function (req, res)
{
   //res.writeHead(200, {'Content-Type': 'text/html'});
   console.log("Server Created!");
   fs.readFile('./html/index.html', function(err, data)
   {

       res.write(data);
       res.end();
   });
}).listen(port);
<!DOCTYPE html>
<html lang="en" dir="ltr">
    <head>
        <meta charset="utf-8">
        <title></title>
        <script src="app.js"></script>
    </head>
    <body>
        <img src="images/2016-collage.jpg"/>
    </body>
</html>

我希望看到网页上显示的图像,但我只是得到损坏的图像链接符号。

【问题讨论】:

标签: html node.js express http


【解决方案1】:

我真的不知道您在 createServer 函数中要做什么,您需要先使用 express 设置路由,然后您的客户才能发出请求。我建议你多读一点文档。

最后,您将需要两条路线,一条用于提供 HTML,另一条用于提供图片:

HTML 路由:

app.get('/', (req, res) => {
    res.sendFile('path_to_html_file.html');
}

图片路线:

app.get('/images/:image', (req, res) => {
    res.sendFile(`path_to_your_images_folder/${req.params.image}`);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-23
    • 1970-01-01
    • 2016-03-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-19
    • 2018-04-05
    • 2012-11-30
    相关资源
    最近更新 更多