Sending Form Data to Node Server

I am trying to send some form data to an endpoint.

Here's my client side code:

<form name="form" action="http://localhost:8080/geodata" method="post"> 

        <label for="minlat"> MinLat: </label>
        <input type="text" name="MinLat" value="0"><br>
        <label for="maxlat"> MaxLat: </label>
        <input type="text" name="MaxLat" value="1"><br>
        <label for="minlong"> MinLong: </label>
        <input type="text" name="MinLong" value="0"><br>
        <label for="maxlong"> MaxLong: </label>
        <input type="text" name="MaxLong" value="1"><br>

        <button type="submit" class="btn btn-success"> Submit <span class="fa fa-arrow-right"></span></button>



    $(document).ready(function() {
            .submit(function(event) {

                var formData = {
                'minLat'            : $('input[name=MinLat]').val(),
                'maxLat'            : $('input[name=MaxLat]').val(),
                'minLong'           : $('input[name=MinLong]').val(),
                'maxLong'           : $('input[name=MaxLong]').val()

                    url: $form.attr('action'),
                    data: formData,
                    cache: false,
                    dataType: 'json',
                    processData: false,
                    type: 'POST',

                    }).done(function(data) {


I have an enpoint on the server side code (express.js):

var express = require("express");
var path = require("path");
var bodyParser = require("body-parser"); 

var app = express();
app.use(express.static(__dirname + "/public"));
  // Initialize the app.
var server = app.listen(process.env.PORT || 8080, function () {
    var port = server.address().port;
    console.log("App now running on port", port);
});"/geodata", function(req, res) {

I wish to send this form data to the endpoint /geodata, and use that data to send a result back to the client side. First of all, when I hit submit, I get an empty {} in my terminal (which is the server side request.body). I was expecting form values in this request.body but don't receive them. How do I make sure my form values are being sent?

Secondly, res.send("hi") re-directs my initial page to a new page and prints "hi" there. Since I had made an ajax call, shouldn't the response just be logged and the webpage stays on the initial page?

Answers 1

  • Change the form action to '/geodata'(the endpoint)

    also you dont need to make a ajax request as HTML5 forms will perform the request itself if a tag() is pressed/clicked.

    after you click summit your page will become what ever response that is sent back from '/geodata' route and req.body will return a object that represents the form data

Related Articles