Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery ajax get to node express, how to get json data?

Tags:

jquery

node.js

I'm trying to send the node instance JSON data using an ajax get request clientside as shown below:

var parameters = { username: 'test' };
    $.ajax({
      url: url,
      data: JSON.stringify(parameters),
      success: function {},
      dataType: 'json'
    });

Using firebug, I can see it sends encoded http://server/web_svc?username=test

in my node express method:

function svc_method(req, res)
{
   var username = req.body.username;
}

req.body.username is undefined. It only works if I post instead of get.

How do I fix this issue? I do have the app.use(express.bodyParser()) line at the top of app.configure().

like image 873
firebird Avatar asked Dec 13 '11 18:12

firebird


People also ask

How JSON fetch data using AJAX?

Approach: To solve this problem, we will first consider a JSON file named “capitals. json” and try to get this JSON data as a response using AJAX. Then we will create an HTML file “capitals. html” which contains a table which we will use to populate the data we are getting in response.

Can we get JSON file using AJAX?

According to the AJAX model, web applications can send and retrieve data from a server asynchronously without interfering with the display and the behavior of the existing page. Many developers use JSON to pass AJAX updates between the client and the server.

How can I get specific data from AJAX response?

You can't as it's asynchronous. If you want to do anything with it, you need to do it in a callback. How? Because it's asynchronous, javascript will fire off the ajax request, then immediately move on to execute the next bit of code, and will probably do so before the ajax response has been received.


1 Answers

You should use req.query.username since you want to get a query string param, check the official Express guide: http://expressjs.com/api.html#req.query

like image 157
alessioalex Avatar answered Nov 09 '22 00:11

alessioalex