如何在Node.js与Express.js中实现前后端变量双向传递
实现客户端与服务端的双向数据传递方案
1. 先准备环境与服务端代码(app.js)
首先安装Express依赖:
npm install express
编写服务端逻辑,创建接口接收客户端数据、处理后返回结果:
const express = require('express'); const app = express(); const port = 3000; // 解析JSON格式的请求体 app.use(express.json()); // 托管静态资源(客户端的html、js文件放在public目录下) app.use(express.static('public')); // 处理计算请求的POST接口 app.post('/handle-calculate', (req, res) => { // 从请求体获取客户端传来的calcul const calcul = req.body.calcul; // 执行计算逻辑 const newCalcul = calcul * 2; // 将结果返回给客户端 res.json({ newCalcul }); }); // 启动服务器 app.listen(port, () => { console.log(`服务器运行在 http://localhost:${port}`); });
2. 客户端代码配置(public目录下)
先创建public/index.html,用来触发客户端逻辑:
<!DOCTYPE html> <html> <head> <title>双向数据传递示例</title> </head> <body> <button onclick="simple()">触发计算流程</button> <script src="script.js"></script> </body> </html>
再编写public/script.js,实现数据发送与结果接收:
function simple() { const calcul = 2 * 2; // 初始计算值为4 // 用fetch发送POST请求到服务端接口 fetch('/handle-calculate', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ calcul }), // 将数据转为JSON格式发送 }) .then(res => res.json()) .then(data => { // 拿到服务端返回的结果,调用simple2打印 simple2(data.newCalcul); }) .catch(err => console.error('请求失败:', err)); } function simple2(newCalcul) { console.log('最终结果:', newCalcul); // 预期输出8 }
3. 运行验证
- 在终端执行
node app.js启动服务 - 打开浏览器访问
http://localhost:3000,点击页面按钮 - 打开浏览器控制台,就能看到打印出的结果
8
内容的提问来源于stack exchange,提问作者Boatti
相关产品推荐
相关产品推荐

