You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js项目中HTML文件浏览器不显示但审查元素可见求助

问题:Node.js项目中HTML内容在浏览器不显示,但审查元素可见

运行Node.js项目时遇到问题:HTML文件内容在浏览器页面上无法显示,但在开发者工具的审查元素中能看到对应内容。已尝试修改端口号,问题依旧;控制台无报错,用console.log输出渲染后的内容也正常,但浏览器页面始终空白。

相关代码

index.js

const http = require("http");
const fs = require("fs");
var requests = require("requests");

const indexFile = fs.readFileSync("index.html", "utf-8");
const replaceVal = (tempVal, orgVal) => {
    let temperature = tempVal.replace("{%tempval%}", orgVal.main.temp);
    temperature = temperature.replace("{%tempmax%}", orgVal.main.temp_max);
    temperature = temperature.replace("{%tempmin%}", orgVal.main.temp_min);
    temperature = temperature.replace("{%location%}", orgVal.name);
    temperature = temperature.replace("{%country%}", orgVal.sys.country);
    return temperature;
}

const server = http.createServer((req, res) => {
    if (req.url == "/") {
        requests("https://api.openweathermap.org/data/2.5/weather?q=akola&units=metric&appid=bbef5cbba9217c339e607bc503f4e700")
            .on("data", (chunk) => {
                const objdata = JSON.parse(chunk);
                const arrData = [objdata];
                const realTimeData = arrData.map((val) => replaceVal(indexFile, val))
                    .join("");

                res.write(realTimeData);
            })
            .on("end", (err) => {
                if (err) return console.log("connection closed due to errors", err);
            });
    }
});

server.listen(15000, "127.0.0.1");

index.html

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet"
        integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
    <link rel="stylesheet" href="style.css">

</head>

<body>

    <div class="position-absolute top-50 start-50 translate-middle ">
        <div class="card cb2" style="width: 18rem; ">
            <div class="card-body text-center text-light">
                <h3 class="card-title">{%location%},{%country%}</h3>
                <h6 class="card-subtitle mb-2 " id="date">Web|Oct 23| 10:49 Am</h6>
                <div class="mt-5">
                    <h5 class="card-title">{%tempval%} C</h5>
                    <h6 class="card-subtitle mb-2 ">Min {%tempmin%} C | Max {%tempmax%} C</h6>
                </div>

            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"
        integrity="sha384-YvpcrYf0tY3lHB60NNkmXc5s9fDVZLESaAA55NDzOxhy9GkcIdslK1eN7N6jIeHz"
        crossorigin="anonymous"></script>

    <script>
        const curDate = document.getElementById("date");
        let weathercon = document.getElementById("weathercon");
        const temStatus = "Clouds";
        const getCurrentDay = () => {
            var weekday = new Array(7);
            weekday[0] = "Sunday";
            weekday[1] = "Monday";
            weekday[2] = "Tuesday";
            weekday[3] = "Wednesday";
            weekday[4] = "Thursday";
            weekday[5] = "Friday";
            weekday[6] = "Saturday";

            let CurrentTime = new Date();
            let day = weekday[CurrentTime.getDay()];
            return day;
        };

        const getCurrentTime = () => {
            var months = [
                "Jan",
                "Feb",
                "Mar",
                "Apr",
                "May",
                "June",
                "July",
                "Aug",
                "Sept",
                "Oct",
                "Nov",
                "Dec",
            ];

            var now = new Date();
            var month = months[now.getMonth()];
            var date = now.getDate();

            let hours = now.getHours();
            let mins = now.getMinutes();
            let perios = "AM";
            if (hours > 11) {
                perios = "PM";
                if (hours > 12) hours -= 12;
            }
            if (mins < 10) {
                mins = "0" + mins;
            }
            return `${month} ${date} | ${hours}:${mins}${perios}`;
        };

        curDate.innerHTML = getCurrentDay() + " " + "|" + " " + getCurrentTime();
    </script>

</body>

</html>

解决方案

问题出在没有结束HTTP响应。当使用res.write()发送内容后,必须调用res.end()来告知浏览器响应已完成,否则浏览器会一直处于等待状态,不会渲染页面。

修改index.js中requests的end事件处理函数,添加res.end():

.on("end", (err) => {
    if (err) return console.log("connection closed due to errors", err);
    res.end(); // 新增这行,结束响应
});

这样浏览器收到完整响应后,就会正常渲染页面内容了。

内容的提问来源于stack exchange,提问作者Prathamesh Rathod

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 22:47:04