[如何使用node.js在前端显示图像?我有一个index.html和index.js文件。带有img路径的img-src似乎不起作用

问题描述 投票:0回答:1

“这些图像在我的js文件中,分别引用了html元素。但是,程序运行后,图标不会出现。还有其他指定路径的方法吗?

node.js openlayers
1个回答
0
投票

确定我了解了我可以回答的问题之后,我相信您正在HTML文件中执行以下操作:

<html>
<body>
    <h1>Test</h1>
    <img src="../ImageNameExample.jpg"></img>
</body>

因为现在您正在将HTML文件发送到客户端,他无法识别图像的路径(src)

一种解决方案是像这样对图像进行获取请求:

        const pathModule = require('path') // save it at the beginning of the script, 
        app.get('/images', (req, res, next) => {
        let name = req.query.imgaeName
        const path = pathModule.join(__dirname, '../../images/')
        res.status(200).sendFile(`${path}${name}`);
    })

并且HTML文件将如下所示:

<html>
<body>
    <h1>Test</h1>
    <img src="http://localhost:8000/images?imgaeName=ImageNameExample.jpg"></img>
</body>

© www.soinside.com 2019 - 2024. All rights reserved.