2013-02-15 46 views
0

从我的网络(客户端)的机器之一返回数据,我正在$.ajax()请求我Nodejs服务器一样,

//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');} 
}); 

和我Nodejs服务器是

//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); 

这些console.log() s工作非常好。我得到我的节点侧发送完全相同的数据,

现在的问题是,在php当我们做一个$.ajax()要求,我们使用echo在我们的PHP文件,将数据发送回客户端,

如果我想将数据发送回客户端,我需要在服务器端做些什么Nodejs (listener.js file)

+1

'response' http://nodejs.org/api/http.html#http_response_end_data_encoding – ashley 2013-02-15 12:52:33

回答

0

解决了这个问题我自己。

问题在于跨域的ajax请求。 我不知道为什么这发生,即使我指定我$.ajax通话url:localhost:8080 ...

解决加入我的响应头 response.setHeader("Access-Control-Allow-Origin", "*"); 问题我。

PEACE

+0

它是跨越原点的,因为HTML文件是使用':80'通过默认的HTTP提供的,而您发布到':8080'则完全不同。为了避免这种情况,您需要设置一个代理来打击或通过Node提供HTML。 – loganfsmyth 2013-02-15 15:33:09

1
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); 

进一步阅读Node.js Documentation

+0

试过......没在'$ .ajax'工作.. :(我的'error'处理器在'客户端'被调用...这个'成功'处理程序何时被调用? – AdityaParab 2013-02-15 12:55:32

+0

正如我刚刚意识到的那样:你在你的代码中指定了一个IP地址,我想你正在得到某种类型的跨域错误 – Viehzeug 2013-02-15 13:04:47

+0

仍然没有运气.. 而关于跨域的事情,现在我在同一台机器上运行两个东西... 让我试着用'--disable-web-security'选项启动谷歌浏览器... – AdityaParab 2013-02-15 13:07:00