i have html page using jqurey . i want to send requests to node server but i don't know how to response to different requests , in other words how to distinguish between get\post request and how read the request body (undreastend what the user wanted) and response according to it.
var http = require("http");
function serve(request, response)
{
response.writeHead(200, {"Content-Type": "text/plain"});
}
http.createServer(serve).listen(3001);
and in the client side , same questin - how to send data ?
Window.onload= function () {
Document.getElementById('GoButton').click=function(){
var xhr = new XHRObject();
xhr.open("get","http://127.0.0.1:1337",true);
xhr.onreadystatechange= function()
{
if (xhr.readyState == 4 && xhr.status == 200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
};
request.send(null);
};
};
and last thing : all this request&response should use json .
To decide what you need to put in your response message, you need to check your request
property. Taking a quick look at the api documentation, you can see that request
is an instance of IncomingMessage, and that it has a property called method
.
If you want to reply something specific for all POST
requests, you should check if request.method === 'POST'
.
Either way, you're apparantly completely new to node, in which case you should probably read up a bit more. http://nodebeginner.org is a good resource to start with.