Reputation: 7100
From one of the machines in my network (client), I am making $.ajax()
request to my Nodejs
server like,
//Client : index.html
$.ajax({
type:"post",
url:'http://192.168.2.6:8080',
data:JSON.stringify({"loginData":{"uanme":"maverick","upass":"asd"}}),
success:function(data){console.log(data);alert(data);},
error:function(){alert('Error aala');}
});
AND my Nodejs
server is
//listener.js
var server = require('http').createServer(function (request, response) {
var body='';
if(request.method=='POST'){
request.on('data',function(data){
body+=data;
});
request.on('end',function(){
console.log(body);
});
}
}).listen(8080);
These console.log()
s are working absolutely fine. I get the exact same data I am sending on the node side,
Now my question is, in php
when we make an $.ajax()
request, we use echo
in our php file to send the data back to the client,
What should I have to do on server side in Nodejs (listener.js file)
if I want to send the data back to the client?
Upvotes: 0
Views: 2091
Reputation: 7100
Solved this problem myself.
The problem was with cross domain ajax requests.
I don't know why this was happening, even though I had specified url:localhost:8080
in my $.ajax
call...
Solved the problem my adding
response.setHeader("Access-Control-Allow-Origin", "*");
in my response headers.
PEACE
Upvotes: 0
Reputation: 1306
var server = require('http').createServer(function (request, response) {
var body='';
if(request.method=='POST'){
request.on('data',function(data){
body+=data;
});
request.on('end',function(){
console.log(body);
//response.setHeader("Content-Type", ""); set the header to your content type
response.write('foo'); // <-----
response.end('Dear client, I have cake for you'); // <-----
});
}
}).listen(8080);
Further reading Node.js Documentation
Upvotes: 1