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().
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With