首页 > 解决方案 > 当我传递实际 URL 时,Img src 标记正在工作,但是当我传递 URL 的常量 instesd 时,它不起作用

问题描述

它只是一个借助开放天气 API 在 HTML 页面上显示天气数据的简单程序。我正在尝试将图像 URL 存储在 imgurl 变量中并将其传递给 img 标签。但我无法获得图像。但是当我在 img 标签中粘贴实际图像 URL 时,它可以工作。我已经通过常量 imgurl 的 console.log 测试了图像 URL,发现它是正确的。我想在 img 标签中传递 imgurl 变量来获取图像。

const express = require('express');

const https = require('https');

const app = express();


app.get('/', function (req, res) {
 
    const url = "https://api.openweathermap.org/data/2.5/weather?q=London&appid=e3b069cb4447ba5b054a354f9ed3f6ba&units=metric";

    https.get(url, function (responce) {

        console.log(responce.statusCode);

        responce.on("data", function (data) {
            const weatherData = JSON.parse(data);
            const temp = weatherData.main.temp;
            const disc = weatherData.weather[0].description;
            const icon = weatherData.weather[0].icon;
            const imgurl = "https://openweathermap.org/img/wn/"+ icon +"@2x.png";
            console.log(imgurl);
            console.log(temp);
            console.log(disc);
            res.write("<h1>The weather is " + disc +"</h1>")
            res.write("<h1>The current temperature in London is " + temp + " degree celsius</h1><br>");
            // when i am passing imgurl in img tag i dont get image
            res.write("<img src='imgurl'>");
            res.send();

        });

    });

});

app.listen(3000, function () {
    console.log("port started at 3000");
});

标签: javascriptnode.jsexpress

解决方案


你没有正确地将图像 url 传递到 url 字段中

尝试:

res.write(`<img src = ${imgurl}>`)

注意它是'不是'


推荐阅读