如何将Node.js获取的MySQL数据传递给前端JS用于页面渲染?
解决方案:Node.js后端数据传递到前端JS
问题本质
Node.js代码运行在服务器环境,前端JS运行在浏览器环境,两者无法直接共享变量,必须通过HTTP接口请求完成数据传递。
步骤1:改造后端代码,搭建HTTP接口
使用Express框架快速搭建接口,将MySQL查询到的movieData通过接口返回给前端。
1.1 安装依赖
在项目根目录执行命令:
npm install express mysql2
(选用mysql2替代mysql模块,支持Promise异步处理,代码更简洁稳定)
1.2 修改后端代码(命名为server.js)
const express = require('express'); const mysql = require('mysql2/promise'); const app = express(); const port = 3000; // 数据库配置 const dbConfig = { host: 'localhost', user: 'root', password: 'root', database: 'films' }; // 定义获取电影数据的接口 app.get('/api/movies', async (req, res) => { let connection; try { // 建立数据库连接 connection = await mysql.createConnection(dbConfig); // 执行查询 const [results] = await connection.execute('SELECT * FROM movietest'); // 转换数据格式为前端需要的结构 const movieData = results.map(element => ({ id: element.id, title: element.name, image: element.image_path, country: element.country, genre: element.genre, description: element.description, year: element.dateRelease, dateHD: element.dateHD })); // 返回JSON格式数据给前端 res.json(movieData); } catch (error) { console.error('数据库查询错误:', error); res.status(500).json({ error: '获取数据失败' }); } finally { // 确保数据库连接关闭 if (connection) await connection.end(); } }); // 托管静态资源(HTML、前端JS、图片等都放在public文件夹) app.use(express.static('public')); // 启动服务器 app.listen(port, () => { console.log(`服务器运行在 http://localhost:${port}`); });
步骤2:改造前端JS代码,请求后端接口
将硬编码的filmsList替换为从后端接口获取的数据,再执行渲染逻辑。
修改前端JS文件(命名为app.js,放在public文件夹内)
// 全局变量存储电影数据 let filmsList = []; const itemsPerPage = 5; let currentPage = 1; const movieContainer = document.querySelector(".movie"); // 创建电影元素的函数保留原逻辑 function createMovieElement(movie){ const movieElement=document.createElement('div'); movieElement.classList.add('slider-info'); movieElement.innerHTML=` <div class="slider-bg "> <a href="#"> <img src="${movie.image}" alt="${movie.title}" > </a> <p>Год выпуска:${movie.year}</p> <p>Жанр: ${movie.genre}</p> <p>Страна: ${movie.country}</p> </div> <div class="favourites"> <button class="favourites_button"> <svg class="favourites_svg" viewBox="0 0 469.33333 469.33333" xmlns="http://www.w3.org/2000/svg"> <path d="m437.332031 192h-160v-160c0-17.664062-14.335937-32-32-32h-21.332031c-17.664062 0-32 14.335938-32 32v160h-160c-17.664062 0-32 14.335938-32 32v21.332031c0 17.664063 14.335938 32 32 32h160v160c0 17.664063 14.335938 32 32 32h21.332031c17.664063 0 32-14.335937 32-32v-160h160c17.664063 0 32-14.335937 32-32v-21.332031c0-17.664062-14.335937-32-32-32zm0 0" /> </svg> <span class="favourites_button_text">В избранное</span> </button> </div> <h2 class="slider-info_title"><a href="#">${movie.title}</a></h2> <span class="slider-info_icons-right ico-red "></span>` return movieElement; } // 分页显示函数适配全局filmsList function displayItemsOnPage(pageNumber) { movieContainer.innerHTML = ""; const startIndex = (pageNumber - 1) * itemsPerPage; const endIndex = Math.min(startIndex + itemsPerPage, filmsList.length); const itemsToShow = filmsList.slice(startIndex, endIndex); itemsToShow.forEach(movie => { const movieElement = createMovieElement(movie); movieContainer.appendChild(movieElement); }); } // 从后端接口获取数据 async function fetchMovies() { try { const response = await fetch('/api/movies'); if (!response.ok) throw new Error('请求失败'); filmsList = await response.json(); console.log('获取到电影数据:', filmsList); // 数据加载完成后渲染第一页 displayItemsOnPage(currentPage); } catch (error) { console.error('获取数据错误:', error); } } // 页面加载时触发数据请求 window.addEventListener('load', fetchMovies);
步骤3:调整项目结构
将静态资源统一放在public文件夹,结构如下:
你的项目文件夹/ ├── server.js # 后端代码 ├── node_modules/ # npm依赖(安装后自动生成) └── public/ ├── index.html # 你的HTML文件 ├── app.js # 前端JS文件 └── img/ # 图片资源文件夹
步骤4:运行项目
- 启动后端服务器:
node server.js
- 在浏览器访问
http://localhost:3000,即可看到从数据库加载的电影数据渲染的页面。
关键说明
- 原Node.js代码与前端JS无法直接共享变量,两者运行环境完全独立:Node.js在服务器,前端JS在浏览器。
- Express是轻量级Node.js框架,适合快速搭建接口,逻辑清晰易上手。
- 使用
mysql2/promise配合async/await处理异步操作,比回调函数更直观,降低出错概率。
内容的提问来源于stack exchange,提问作者John Shevchenko
相关产品推荐
相关产品推荐

