thesydne
thesydne

Reputation: 127

Get a value of a received JSON by ajax in nodejs

I'm using jquery to get a date and send it by ajax to a nodejs server. I'm getting the e.date by a daterangepicker.

            var minFecha = new Date(e.date);
            var data = {};
            data.min = minFecha;
            $.ajax({
                type: 'GET',
               data: JSON.stringify(data),
                contentType: 'application/json',
                url: '/dat/',                       
                success: function(data) {
                    console.log('success   '+data);
                   // console.log(JSON.stringify(data));
                }
            });

And i have this in server.js

app.get("/dat/", function(req, res){
  console.log("data received  " + JSON.stringify(req.query));
});

In the console I get this : data received {"{\"min\":\"2018-01-09T23:00:00.000Z\"}":""}

Now I need to get the date "2018-01-09T23:00:00.000Z" in a var. I was using JSON.parse and req.query['min']: var obj = JSON.parse(JSON.stringify(req.query)); console.log("TEST "+obj['min']); But this way doesn't work, it returns undefined. Any solution?

Upvotes: 1

Views: 116

Answers (1)

YouneL
YouneL

Reputation: 8351

There is no need to use stringify, just pass your data to data property in the ajax object and it should work:

client

$.ajax({
    type: 'GET',
    data: data,
    contentType: 'application/json',
    url: '/dat',                       
    success: function(data) {
        console.log('success   '+data);
        // console.log(JSON.stringify(data));
    }
});

Server

app.get("/dat", function(req, res){
    console.log("data received  " + req.query.min);
});

Upvotes: 1

Related Questions