简体   繁体   中英

how to read html request body from nodejs by name

Hi I want to read radio button check result from html page

I made this html page

<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>
            <% } %>
    <% } %> 
<% } %> 

Finished

questionList and answerList are array to show question and answer

I want to get a result to my nodejs router my current code is below

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

but I got an error TypeError: Cannot read property '0' of undefined at /home/kwon/NODE/TASK/myChat/routes/routes.js:298:37 at callbacks

If I print log of req.body then I got result below

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

so I think they are saved in well in req.body I don't know how to read 'Howoldareyou' and 'Whatisyourfavorit' data (each are stored in questionList)

Try this:

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

伙计,您需要bodyparser模块以这种方式接收数据,以检查bodyparser代码是否过旧,因为bodyparser早已包含在express中,但现在不再可用

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM