Skip to content Skip to sidebar Skip to footer

How Do I Access Ejs Data In A Form While Using Express

In the following code, I display the following HTML file upon user requests. I also want to access the clubname and type datavalues inside my app.post() function in my app.js file.

Solution 1:

Let's start with getting the info into the form. Edit the form like so:

<formaction="/clubreq"method="post">
    <% for (var i in clubreq){%>
        Club Name: <inputtype="text"name="clubname[]"value="<%= clubreq[i].clubname %>" /><br><br>
        Club Type: <inputtype="text"name="clubtype[]"value="<%= clubreq[i].type %>" /><br><br><inputtype="submit"value="accept"/><br><br><hr>
    <%} %>
</form>

The important points being adding the action attribute indicating where to submit the form and the addition of inputs to ensure the values and transported with the form. If you don't like the way it looks, you can change the input type to hidden and then add another echo like you had before of club name and club type for the end user to see.

Now on to how to access your form data server side, add the following to the top with all your other middleware:

app.use(express.bodyParser());

Next, you can access the post data in your method like so:

app.post('/clubreq', function(req, res, next){
   // req.body object has your form valuesconsole.log(req.body.clubname);
   console.log(req.body.clubtype);
});

Hope that helps

Post a Comment for "How Do I Access Ejs Data In A Form While Using Express"