How to get data in express from post route?

How to get data in express from post route?


Currently, i am doing voting app.
and in express when I use ejs as view engine it is very easy to send data like


but when to fetch data from some page we have to use middleware like body-parser. and using body parser i know how to get data like this way bellow

 <form method="POST" action="/newpoll" 
      <input type="text"name="title" id="title">
      <button type="submit" >Submit</button>

    console.log(req.body);  //{title:'mytitle"}     

Now the question are
1.if i want to send some additional with title for example who create the poll what are the possible way ? can i send custom json data to post route (cant find any example :confused: )
3.can i use both JSON body parser and URL-encoded form body parser in same route ?


1] If you only needed a small amount of additional information, you could add hidden form fields like this:

 <form method="POST" id="yourForm" action="/newpoll" 
      <input type="hidden" name="pollCreator" value="Me">
      <input type="text"name="title" id="title">
      <button type="submit" >Submit</button>

2] Javascript can definitely help you post-process a form before submission. Checkout this link for a couple different methods.

One example, using jQuery, might go like this.

$(function() {
    $('#yourForm').on('submit', function(e) {
        e.preventDefault();  //prevent form from submitting
        var data = $("#login_form :input").serializeArray();
        data.myAdditionalProperty = "something";
        $.post( "/to/your/server", data );

you could also use jQuerys .submit() function to affect the forms action.

3], not sure, to be honest. I don’t see why not.
app.use(bodyParser.urlencoded({extended: true}));

then process your routes for both sets of information.


i wanted to pass a json data, so insted of this

 <input type="hidden" name="pollData" value="Me">

i tried json.stringify

<input type="hidden" name="pollData" value=" <%= json.stringify(myJsonObject) %>">

but for some reson
insted of getting this type of data

 pollData:{"_id":"587e8d535149b6165cd15266","title":"title 2","__v":0,"options":["op 1","op 2","op 3"]},
 pollSelectedValue: 'op 2' 

i am geting

 pollData: '{"_id":"587e8d535149b6165cd15266","title":"title',
 pollSelectedValue: 'op 2' 

for some reason it skip value from __v.

but i had no idea about 2nd way given above hopefully now i can pass the json object along side form data :smiley:

thanks for short clean and effective answer :slight_smile: