You need to enable JavaScript to run this app. 如何编写Node.js代码让本地图片在localhost访问时浏览器正常加载
优惠活动
大模型
产品
解决方案
定价
更多

如何编写Node.js代码让本地图片在localhost访问时浏览器正常加载

解决方案

第一步:修正后端index.js代码

你现有代码存在两个核心问题:

  • 注释了静态资源托管配置,导致浏览器无法从服务端获取图片等静态文件
  • 把浏览器端运行的DOM操作函数、数据库逻辑错误写在了后端代码中,后端运行在Node.js环境,无法直接操作浏览器DOM,且数据库操作绝对不能放在前端暴露账号密码

修改后的完整index.js代码:

// 导入Node.js依赖模块
var express = require("express");  
var app = express();  
var path = require("path");
var cors = require("cors"); 
var mysql = require('mysql');
var port = 3000;  

// 启用静态资源托管,直接映射你的项目根目录,该目录下的图片、html、前端js都可直接访问
app.use(express.static("D:/Behrans-files/Web-projects/havuzlusite"));
app.use(cors());
app.use(express.urlencoded({ extended: true }));
app.use(express.json());

// 数据库连接配置(放在后端不会泄露)
var con = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: 'hsAdmin',
    database: 'havuzsDB'
});
con.connect(function(err) {
    if (err) throw err;
    console.log("数据库连接成功!");
});

// 登录接口,处理前端提交的账号密码校验
app.post('/login', (req, res) => {
    const { isim, sifre } = req.body;
    // 参数化查询避免SQL注入
    const sql = 'select * from havuzs_sakinleri where isim = ? && sifre = ?';
    con.query(sql, [isim, sifre], function(err, results) {   
        if (err) {
            return res.status(500).json({msg: '数据库查询出错'});
        }
        if (results.length !== 1) {
            return res.status(400).json({msg: '用户名或密码错误'});
        }
        res.json({
            msg: '登录成功',
            userInfo: results[0]
        })
    }); 
})

// 启动服务,注意端口要和你配置的port一致
app.listen(port, () => {
    console.log(`服务运行在 http://127.0.0.1:${port}`);   
});

第二步:修正前端index.html代码

  • 移除本地绝对路径的资源引用,改用静态资源托管后的相对路径
  • 把DOM操作的前端逻辑移到页面内的script标签中
  • 调整登录逻辑,前端提交表单请求后端接口

修改后的核心部分代码:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" content="width=device-width, initial-scale=1">
    <title>Havuzlu Site</title>
    <style>
        /* 背景图路径保持/havuzlusite_img.jpg即可,和实际文件名保持一致 */
        html {
            background-image: url("/havuzlusite_img.jpg"); 
            background-repeat: no-repeat; 
            background-position: center center; 
            background-attachment: fixed; 
            background-size: cover;
        }
        /* 其余原有样式保持不变,直接保留即可 */
    </style>
</head>  
<body>
    <h1>Havuzlu siteye hoş geldiniz</h1>
    <button class="button1">Site haberleri</button>
    <button class="button2">Site yönetimi</button>
    <button class="button3" onclick="openForm()">Aidat takibi</button>
  
    <div class="login-form" id="loginform">
        <form class="login-fields" id="loginForm">
            <h1>Kullanıcı girişi</h1>
            <label for="isim"><b>isim</b></label>
            <input type="text" placeholder="İlk ve soy isim giriniz" id="isim" name="isim" required>
            <label for="sifre"><b>şifre</b></label>
            <input type="password" placeholder="Şifre giriniz" id="sifre" name="sifre" required>
            <button type="button" class="btn-login" onclick="validateuser()"> Giriş</button>
            <button type="button" class="btn-cancel" onclick="closeForm()"> Kapat</button>
        </form>
    </div>
    <!-- 图片路径修改为静态资源路径 -->
    <img src="/havuzlusite-img.jpg" alt="背景图">

    <script>
        // 前端DOM操作逻辑移到此处
        function openForm() {
            document.getElementById("loginform").style.display = "block";
        }

        function closeForm() {
            document.getElementById("loginform").style.display = "none";
        }

        // 登录校验逻辑改为请求后端接口
        async function validateuser() {
            const input_isim = document.getElementById("isim").value;
            const input_sifre = document.getElementById("sifre").value;
            
            try {
                const res = await fetch('http://localhost:3000/login', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        isim: input_isim,
                        sifre: input_sifre
                    })
                })
                const data = await res.json();
                alert(data.msg);
                if(res.ok) {
                    // 登录成功后的逻辑,比如展示用户信息
                    console.log(data.userInfo);
                }
            } catch(e) {
                alert('请求出错,请检查服务是否运行');
            }
        }
    </script>
</body>  
</html>

注意事项

  • 请确认图片文件名和代码中引用的文件名完全一致,注意下划线、横杠的区别
  • 启动服务前请先安装所需依赖:npm install express cors mysql
  • 后续所有静态资源(css、js、图片等)都放到项目根目录下,直接用/文件名的路径引用即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.08 09:33:02