ExpressJS POST请求推送数组值为undefined问题求助
问题解决:POST请求推送数据到数组出现undefined
问题描述
实现POST请求将new-quote页面的名言和作者信息推送到数组时,console.log能正常打印输入值,但数组中添加的却是undefined值,尝试多种写法均未解决。
核心问题分析
问题出在pushQuote函数的调用传参上:
- 你定义的
pushQuote需要两个独立参数quoteText(名言内容)和attribution(作者) - 但调用时传入的是一个对象
{quote, person},导致第一个参数quoteText变成这个对象,第二个参数attribution为undefined,最终数组中插入的内容完全不符合预期
另外前端处理返回值时也存在解构错误,会导致页面渲染异常。
修改方案
1. 修正Server.js中的函数调用
将错误的传参方式改为传入两个独立参数:
// 原错误调用 pushQuote({quote, person}); // 修改为 pushQuote(quote, person);
完整修正后的Server.js相关代码段:
app.post('/api/quotes', (req, res, next) => { const quote = req.query.quote const person = req.query.person function pushQuote (quoteText, attribution) { quotes.push({quote:quoteText, person:attribution}); } if(quote && person){ console.log(quote) console.log(person) console.log(quote, person) pushQuote(quote, person); // 修正传参 res.status(201).send({quote:quote, person:person}); } else { res.status(400).send("There was an error processing the request. Please try again.") } });
2. 修正前端add-quote.js的返回值处理
后端返回的是包含quote和person属性的对象,原代码解构{quote}只会拿到名言字符串,无法访问.quote和.person属性,需调整解构逻辑:
// 原错误解构 .then(({quote}) => { // 修改为 .then((newQuote) => {
同时更新模板中的变量引用:
newQuote.innerHTML = ` <h3>Congrats, your quote was added!</h3> <div class="quote-text">${newQuote.quote}</div> <div class="attribution">- ${newQuote.person}</div> <p>Go to the <a href="index.html">home page</a> to request and view all quotes.</p> `
完整修正后的add-quote.js代码:
const submitButton = document.getElementById('submit-quote'); const newQuoteContainer = document.getElementById('new-quote'); submitButton.addEventListener('click', () => { const quote = document.getElementById('quote').value; const person = document.getElementById('person').value; fetch(`/api/quotes?quote=${quote}&person=${person}`, { method: 'POST', }) .then(response => response.json()) .then((newQuote) => { const newQuoteElement = document.createElement('div'); newQuoteElement.innerHTML = ` <h3>Congrats, your quote was added!</h3> <div class="quote-text">${newQuote.quote}</div> <div class="attribution">- ${newQuote.person}</div> <p>Go to the <a href="index.html">home page</a> to request and view all quotes.</p> ` newQuoteContainer.appendChild(newQuoteElement); }); });
内容的提问来源于stack exchange,提问作者jon raynes
相关产品推荐
相关产品推荐

