【问题标题】:how to read html request body from nodejs by name如何按名称从nodejs读取html请求正文
【发布时间】:2015-07-05 15:46:20
【问题描述】:

您好,我想从 html 页面读取单选按钮检查结果

我制作了这个html页面

<form action="/question" method="post">
<% for (var i = 0; i < questionList.length; i++) { %>
    <h1> <%= questionList[i] %> </h1> <br>

    <% for (var j = 0; j < answerList[i].length; j++) { %>
        <% if(j === 0) { %>
            <input type="radio" name="<%= questionList[i] %>" id="<%= questionList[i] %>" value="<%=answerList[i][j] %>" checked="checked"> <%=answerList[i][j] %> <br>
        <% } %>

        <% if(j > 0) { %>
            <input type="radio" name="<%= questionList[i] %>" id="<%= questionList[i] %>" value="<%=answerList[i][j] %>"> <%=answerList[i][j] %> <br>
            <% } %>
    <% } %> 
<% } %> 

完成

questionList 和 answerList 是显示问题和答案的数组

我想得到一个结果到我的 nodejs 路由器 我当前的代码如下

app.post('/question', function(req, res){
    for(var i=0; i<questionList.length; i++){
        console.log(req.body.questionList[i]);
    }
});

但我收到一个错误TypeError: Cannot read property '0' of undefined at /home/kwon/NODE/TASK/myChat/routes/routes.js:298:37 at callbacks

如果我打印 req.body 的日志,那么我会在下面得到结果

{ 'Howoldareyou? ': '20', 'Whatisyourfavorite? ': 'sports' }

所以我认为它们在 req.body 中保存得很好 我不知道如何阅读“Howoldareyou”和“Whatisyourfavorit”数据(每个都存储在 questionList 中)

【问题讨论】:

  • questionList 长什么样子?
  • questionList 只是一个包含问题列表的字符串数组 我的代码是 var questionList=[]; 我推送从 .txt 文件中读取的数据并将它们存储在上面的变量中
  • 但错误显示 questionList 未定义。试试看它是否有值。
  • 我已经检查过了。有价值

标签: javascript html node.js express


【解决方案1】:

试试这个:

app.post('/question', function(req, res){
    for(var i=0; i<questionList.length; i++){
        console.log(req.body[questionList[i]] );
    }
});

【讨论】:

【解决方案2】:

伙计,你需要 bodyparser 模块来接收来自这种方式的数据检查 bodyparser 代码可能是旧的,因为 bodyparser 在过去包含在 express 中,但现在不再包含

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-07
    • 2023-03-29
    • 2013-04-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-21
    相关资源
    最近更新 更多