req.query is the query string sent to the server, example:
req.query will return a JS object after the query string is parsed.
for example:
/user?name=tom&age=55 – req.query would yield {name:”tom”, age: “55”}
req.param is the parameters passed to the handler.
app.get(‘/user/:id’, handler);, going to /user/blah,
req.param.id would return blah;
In the example, we have a contact form where there are textfields and a button.
The button id is #send_email, which we bind a click event to it.
Once that button is clicked, we come to the ‘click’ event handler for #send_email and then get all the value from the textfields by using val().
Once that’s done, we want to give the contact data to the server and GET us a response saying the data has been sent to an email box. Hence we use jQuery’s GET function where:
1) we give it the URL we want to access
2) the object with the data
3) completion function definition
We check to see if the result says ‘sent’. If it does, we know that the server have successfully sent it. If not, we know something went wrong and it has not been sent.
.html file
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
$(document).ready(function(){ var from,to,subject,text; $("#send_email").click(function(){ console.log('send mail clicked'); from = $("#from").val(); subject = $("#subject").val(); text = $("#content").val(); $("#message").text("Sending E-mail...Please wait"); $.get("http://localhost:3000/send", //URL {from:from,subject:subject,text:text}, //object with data function(data) { //completion function definition console.log('response data: ' + data); if(data=="sent") { $("#message") .empty() .html("Message received. We'll get right back to you within 24 hrs"); } else { $("#message") .empty() .html("oops, something went wrong: " + text); } }); //get }); //click event }); </script> |
Once the $.get method fires in the .html file, we come to the ‘GET’ handler in our server code.
From there you access the object data that’s been sent by the client’s jQuery $.get method by using req.query.—-, where —- is the key.
server.js
1 2 3 4 5 6 7 |
app.get('/send',function(req,res){ console.log('from: ' + req.query.from); console.log('subject: ' + req.query.subject); console.log('text: ' + req.query.text); ......... ......... |
….
….
somewhere after you do your processing, you need to send back a confirmation. We do this using res.end() and whatever object you use will be checked by your client’s jQuery’s $.get completion function definition(3), as listed above.
1 2 3 4 5 6 7 |
if(error){ console.log(error); res.end("error"); } else { console.log("Sending str sent back to .get function on client"); res.end("sent"); } |
Note req.end:
With http.request() one must always call req.end() to signify that you’re done with the request – even if there is no data being written to the request body.