简体   繁体   中英

Format of data received through ajax request?

I have client side code that looks like this:

<form name="sendCoordinates" action="http://localhost:8080/geodata" method="post"> 
        <label> MinLat: </label>
        <input type="text" name="MinLat" value="0"><br>
        <label> MaxLat: </label>
        <input type="text" name="MaxLat" value="1"><br>
        <label> MinLong: </label>
        <input type="text" name="MinLong" value="0"><br>
        <label> MaxLong: </label>
        <input type="text" name="MaxLong" value="1"><br>

        <input type="submit" value="submit" id="s1">
        </form> 

<script>


        $("#sendCoordinates")
            .on('submit', function(e) {

                e.preventDefault();

                var $form    = $(e.target),
                    formData = new FormData();
                    params   = $form.serializeArray();

                $.each(params, function(i, val) {
                    formData.append(val.name, val.value);
                });

                $.ajax({
                    url: $form.attr('action'),
                    data: formData,
                    cache: false,
                    contentType: false,
                    processData: false,
                    type: 'POST',
                    success: function(result) {
                        console.log(result + "you");
                    }
                });
            });
    </script>

I am sending this form data to an endpoint /geodata .

app.post("/geodata", function(req, res) {
    console.log(req.body);
});

My question is, under a successful post, what would console.log(req.body) print on the server side? I am unable to tell yet as my client is not sending any information yet due to some bug. This will help me write my server side code according to the data I receive in the post request.

Looks like you're using Express. In general practice, request bodies are parsed as JSON (see Express req.body docs ), but it depends on the parsing middleware you're using ( body-parser is the common one in Express apps).

It also depends on the Content-Type header of the request. From the Express docs I mentioned above, they give an example:

app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded

It looks like you currently set contentType: false in your AJAX request, so that will just send raw data to your server.

To answer your question more concretely

My question is, under a successful post, what would console.log(req.body) print on the server side?

It depends on the Content-Type and what middleware (if any) you are using the parse request bodies.

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