5

This is my ajax request call

  $.ajax({
    url: '/refresh',
    type: 'GET',
    contentType: "application/json",
    data: {
        Name: $("#inputName").val(),
        Url: $("#inputUrl").val()
    },
    success: function(data) {
        console.log('form submitted.' + data);
    }
  });

This is the GET route in nodejs

app.get('/refresh', function(req, res) {
            console.log("My data" + JSON.stringify(req.body));
            //other operations
        }

How can i get the data which is passed from ajax call in my js?? Please help!! Thanks a lot!

Ramya S
  • 2,954
  • 5
  • 14
  • 24

2 Answers2

5

jQuery's .ajax() method sends the data property as a query string for GET requests, so in your Express code you have to retrieve that data from req.query instead of from req.body.

Arnelle Balane
  • 5,437
  • 1
  • 26
  • 32
2

You can simply use req.query for that:

const id = req.query._some_query_param; // $_GET["id"]

// Sample URL: https://foo.bar/items?id=234
app.get("/items",function(req,res){
   const id = req.query.id;
   //further operations to perform
});

If you want to get the route parameters you could use req.params which only gets the route parameters and not the query string parameters.

For example:

// Sample URL: https://foo.bar/items/322
app.get("items/:id",function(req,res){
 const id = req.params.id;
 //further operations to perform
});
Suhail Gupta
  • 22,386
  • 64
  • 200
  • 328