0

My issue is my form is submitting (to a node/express api), and if I console.log the req.body (@ the api) the result is an empty object. However if i console.log on the client the serialized string has data.

Read thru other posts - their problems are not the same, so the solutions posted did not work for me.

    <form class="newsletter-form  clearfix" method="post" action="/subscribe" role="form" id="frmSubscribe" >
        <div class="form-group " >
            <label for="newsletter-signup" >Subscribe</label>
            <input type="email" class="form-control input-sm" id="newsletter-signup" name="email" placeholder="Email Address">
            <button type="button" id="subscribe" class="btn btn-default black-button" >Subscribe Now!</button>
        </div>
    </form>

And the JS

<script>
    $( document ).ready( function () {          

        $("#subscribe").click(function(){

            $.ajax({
                type: "POST",
                url: "/subscribe",
                data: $("#frmSubscribe").serialize(),
                success: function(msg) {                        
                    alert('Thank You, You are now Subscribed.');
                },
                error: function(err){
                    alert('Uh-oh, even the subscription form is mis-behaving!');
                }
            });
        });

    });
</script>

And the code at '/subscribe'

.post( (req, res) => {

    console.log( 'subscribe = ' + JSON.stringify( req.body ) );

});

The results of '/subscribe' look like this.:

subscribe = {}

While the results of console.log( $("#frmSubscribe").serialize() ) look like this

email=whatever-i-type

Scratching my head - sure I'm missing something obvious....Thx ahead of time.

One thing that may be effecting this is this form is on an index page that is th entry point of an angular 2 app. however - like I stated, the console.log on the client spits out the correct info - so I'm fairly sure the jquery lib is seeing the form correctly, and submitting to the correct api path - as my api 'log' is outputting - it just seems as though the object being passed is empty.

If it helps - if I take out all the JS, and just change my form to use 'input type='submit' - the form doesn't even submit - it does nothing - yes, I removed the listener, there should be nothing interfering. but maybe there is.

j-p
  • 3,698
  • 9
  • 50
  • 93

1 Answers1

1

Note that you are not explicitly specifying content-type. By default, jQuery uses content-type of 'application/x-www-form-urlencoded; charset=UTF-8' with post. In this case, you'll be receiving url encoded string content on the server not JSON.

Check this answer - on how to parse content for specific version of Express you are using.

VinPro
  • 882
  • 1
  • 6
  • 10
  • Specifically: Adding this to my express app. app.use(bodyParser.urlencoded({ // to support URL-encoded bodies extended: true })); – j-p Mar 11 '18 at 04:09