繁体   English   中英

图像未在 Express JS 中加载

[英]Image not loading in Express JS

在 Express 中,我编写了以下代码行:

res.write("The current temperature is "+temp+". ");
res.write("Weather is currently "+weatherDes);
res.write("<img src=" +imageURL+ ">");
res.send();

但是图像没有加载。 任何人都可以帮忙吗?

我建议使用“res.send”

const express = require('express')
const app = express()
const port = 3000

app.get('/', (req, res) => {
    const temp = 10;
    const weatherDes = 20;
    const imageURL = "https://dog.png";

    let html = "The current temperature is: " + temp + ".\n";
    html += "Weather is currently: " + weatherDes + ".\n"
    html += '<img src="' + imageURL +'" width="50" height="50">';

    res.send(html);
})

app.listen(port, () => {
    console.log(`Example app listening at http://localhost:${port}`)
});

或者更好的方法是使用像 ejs 这样的“视图引擎”

const express = require('express')
const app = express()
const port = 3000

// set the view engine to ejs
app.set('view engine', 'ejs');

// use res.render to load up an ejs view file

// index page 
app.get('/', function(req, res) {
    const data = {
        temp: 10,
        weatherDes: 20,
        imageURL: 'https://dog.png'
    };
    res.render('pages/index', data);
});

app.listen(port, () => {
    console.log(`Example app listening at http://localhost:${port}`)
});

如果您决定像上一个示例一样使用 ejs,则需要创建一个包含以下内容的文件“/views/pages/index.ejs”:

<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>Your Website</title>
</head>
<body>
    <p>The current temperature is: <%= temp %> </p>
    <p>Weather is currently: <%= weatherDes %> </p>
    <img src="<%= imageURL %>" width="50" height="50">
</body>
</html>

不要忘记安装 ejs

npm i ejs

并用您的图片更改“https://dog.png”

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM