0

I am trying to send json data through ajax call. Following is the code I used. I'm using node.js as the backend. a_filters,b_filters,etc. are arrays. I googled the error but couldn't get the code to work.

var filters =
                {
                    "a" : a_filters,
                    "b" : b_filters,
                    "c" : c_filters,
                    "d" : d_filters
                };
        $.ajax({
            url : "query/get-filtered-data",
            dataType : 'json',
            async: "true",
            data:JSON.stringify(filters),
            contentType: 'application/json; charset=utf-8',
            success : function(data){


            },
            failure: function(data){
                alert('got an error');
            }
        });

EDIT : This is my server-side code.

var express = require('express');
var router = express.Router();

//the URL below is correct since it redirects from 'query/'
router.get('/get-filtered-data', function (req, res, next) {

    console.log(req);    
    var filters = JSON.parse(req.body);
    console.log("foo");
    var a_filters = filters["a"];
    var b_filters = filters["b"];
    var c_filters = filters["c"];
    var d_filters = filters["d"];

    res.send(query);
});

conosle.log('foo') doesn't print anything. console.log(req) has req.body empty. Thanks a lot in advance.

1 Answers1

0

Because you are referencing req.body, you need to use a router method that includes a body - post or put.

You may also need to include type: "POST" in your jQuery Ajax method.

There is a more general semantic question about whether you should use get with a query string to communicate parameters when retrieving data rather than using a request body, but that is an API design question rather than a cause of errors.

Chris
  • 1,644
  • 1
  • 11
  • 15