如何将前端script.js的数组发送至Express的index.js?
问题描述
我尝试将前端script.js中的数组cArray(或JSON对象)发送至Express服务端的index.js时遇到困难。试过多种方法:将变量传递到HTML再转至其他JS文件(不适用于当前场景)、使用localStorage(无法在Node环境中使用)、通过POST请求传输但未能正确构造请求内容。经验尚浅,希望得到帮助,相关代码如下:
服务端代码(index.js)
var express = require('express'); var path = require('path'); var app = module.exports = express(); var engines = require('consolidate'); var fs = require('fs'); app.engine('php', engines.mustache); app.set('view engine', 'php'); app.set('views', path.join(__dirname, '/views/')); app.use(express.static(path.join(__dirname, './public'))); app.get('/', function(req, res){ res.render('index.php'); }); if (!module.parent) { app.listen(3000); console.log('Express started on port 3000'); } function submitColors(e) { fs.writeFile("./colors.txt", JSON.encode(e), (err) => { if(err){ console.log(err); } else{ console.log("Successfully sent JSON to colors.txt (Array: " + e + " and JSON " + JSON.encode(e)); } }); } app.get('/colors', function(req, res) { submitColors(cArray); res.render('index.php'); res.send('Colors maybe sent successfully?'); });
前端页面(index.php,无PHP代码)
<div id="buttons-div"> <button id="yellow-button" onclick="changeColor('yellow')"></button> <button id="red-button" onclick="changeColor('red')"></button> <button id="blue-button" onclick="changeColor('blue')"></button> <button id="white-button" onclick="changeColor('white')"></button> <button id="green-button" onclick="changeColor('green')"></button> <form method="POST" action="colors"> <input id="submit" type="submit"></input> </form> </div>
前端脚本(script.js)
function changeColor(e) { if(e == "red") { console.log('red'); addColor('red'); } else if (e == "blue") { console.log('blue'); addColor('blue'); } else if (e == "green") { console.log('green'); addColor('green'); } else if (e == "yellow") { console.log('yellow'); addColor('yellow'); } else if (e == "white") { console.log('white'); addColor('white'); } } function isInArray(array, string) { if(array.indexOf(string.toString()) >= 0) { console.log(array.indexOf(string.toString()) + " true and is inside"); return true; } else if (array.indexOf(string.toString()) < 0){ console.log(array.indexOf(string.toString()) + " false and is not inside"); return false; } } var cArray = []; function addColor(c) { if(isInArray(cArray, c) == true) { var a = cArray.indexOf(c.toString()); delete cArray[a]; console.log('deleted ' + c + ' from the list'); return true; } else { cArray.push(c.toString()); console.log('added color ' + c + ' to the list'); } }
解决方案
1. 配置服务端解析JSON请求体
Express默认不会自动解析JSON格式的请求体,需要添加中间件开启该功能。在app.use(express.static(...))之后添加:
app.use(express.json());
2. 修复服务端接口与数据处理逻辑
- 将
GET /colors接口改为POST(提交数据用POST更符合语义) - 从请求体
req.body中获取前端传来的数组 - 修复
JSON.encode的错误(正确方法是JSON.stringify)
修改后的服务端相关代码:
function submitColors(e) { // 过滤数组中因delete产生的空值,避免写入无效数据 const filteredColors = e.filter(color => color !== undefined); fs.writeFile("./colors.txt", JSON.stringify(filteredColors), (err) => { if(err){ console.log(err); } else{ console.log("Successfully saved colors: ", filteredColors); } }); } // 改成POST接口 app.post('/colors', function(req, res) { // 从req.body拿前端传来的colors数组 const colorsArray = req.body.colors; if (colorsArray && Array.isArray(colorsArray)) { submitColors(colorsArray); res.send('Colors saved successfully!'); } else { res.status(400).send('Invalid data: expected an array of colors'); } });
3. 修改前端提交逻辑
原表单没有携带cArray数据,需要用JavaScript发送带JSON数据的POST请求:
- 修改页面中的表单,换成按钮调用自定义提交函数
- 在
script.js中添加发送请求的函数
修改后的前端页面:
<div id="buttons-div"> <button id="yellow-button" onclick="changeColor('yellow')"></button> <button id="red-button" onclick="changeColor('red')"></button> <button id="blue-button" onclick="changeColor('blue')"></button> <button id="white-button" onclick="changeColor('white')"></button> <button id="green-button" onclick="changeColor('green')"></button> <!-- 换成按钮调用提交函数,避免默认表单提交 --> <button id="submit" onclick="sendColors()">Submit Colors</button> </div>
在script.js末尾添加发送函数:
function sendColors() { fetch('/colors', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ colors: cArray }), }) .then(response => response.text()) .then(data => { console.log('Server response:', data); alert(data); }) .catch(error => { console.error('Error sending data:', error); alert('Failed to send colors'); }); }
4. 额外优化(可选)
前端addColor函数中用delete会留下空值,建议用splice删除元素,避免数组出现无效项:
function addColor(c) { const index = cArray.indexOf(c.toString()); if(index !== -1) { // 用splice删除对应位置的元素,不会留下空值 cArray.splice(index, 1); console.log('deleted ' + c + ' from the list'); return true; } else { cArray.push(c.toString()); console.log('added color ' + c + ' to the list'); } }
修改完成后,点击Submit按钮即可将cArray中的颜色数组发送至服务端,服务端会将数据写入colors.txt文件。
内容的提问来源于stack exchange,提问作者user19430065
相关产品推荐
相关产品推荐

