Изображение не загружается в Express JS - PullRequest
0 голосов
/ 04 августа 2020

В Express Я написал эти строки кода:

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

Но изображение не загружается. Кто-нибудь может помочь?

1 Ответ

0 голосов
/ 04 августа 2020

Я рекомендую использовать «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}`)
});

Или лучше использовать «механизм просмотра», например e js

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}`)
});

Если вы решите использовать e js как и в последнем примере, вам нужно создать файл "/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>

Не забудьте установить e js

npm i ejs

И замените «https://dog.png» своим изображением

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...