2016-09-30 230 views
1

我正在使用AJAX POST数据到服务器使用Node.js代码。很简单,这个测试项目中有两个文件。这里是main.htmlAJAX发送数据到Node.js服务器

<!DOCTYPE HTML> 
<html> 
    <head> 
    </head> 
    <body> 
     <script> 
      var xhr = new XMLHttpRequest(); 
      xhr.open('POST', '/', true); 
      xhr.send('hello'); 
     </script> 
    </body> 
</html> 

这里的服务器代码:

const http = require('http'); 

http.createServer(function(req,res) { 
    console.log(req.body); 
}).listen(3000); 

也许,你已经知道,服务器将console.log() '未定义'。 所以问题是为什么它'未定义'?如何获得服务器上的AJAX数据?

我知道this question的其他解决方案。

你能帮助我任何其他方式来方便地获取数据吗?

+0

您是否为''/''定义了任何路线? – abdulbarik

+0

@abdulbarik谢谢,我认为http.createServer会收到任何请求。不管路线如何。 – suoyong

回答

3

您已经创建的服务器还好吧,但有两个问题:

  1. 连接端点。你的AJAX是POST,所以你需要正确解析POST请求(不完全解决你的问题,但你需要区分请求方法)。
  2. Node.js的默认情况下不解析您POST的身体,你需要告诉它,它是如何做的,通过使用querystring模块,例如。

两者结合,这样的:

var qs = require('querystring'); 

http.createServer(function(req, res) { 
    if (request.method == 'POST') { 
     var body = ''; 

     request.on('data', function(data) { 
      body += data; 
     }); 

     request.on('end', function() { 
      var post = qs.parse(body); 

      // Use your POST here 
      console.log(post); 
     }); 
    } 
}).listen(3000); 

JSON数据 - 清洁的解决方案:

你需要用JSON编码您的AJAX的数据,比解析它在服务器端像这样:

http.createServer(function(req,res) { 
    if (req.method == 'POST') { 
     var jsonPost = ''; 

     req.on('data', function(data) { 
      jsonPost += data; 
     }); 

     req.on('end', function() { 
      var post = JSON.parse(jsonPost); 

      // Use your POST here 
      console.log(post); 
     }); 
    } 
}).listen(3000); 

你会更好使用Express.js框架,与它的bodyParser模块。


更新 - 块是如何缓冲:

考虑简单的例子 - 在xhr.send()发送文本的量,超过Content-Length。比起做data事件如下:

req.on('data', function(data) { 
    console.log(data); 
    body += data; 
}); 

你会看到类似这样的:

<Buffer 0a 0a 4c 6f 72 65 6d 20 69 70 73 75 6d 20 64 6f 6c 6f 72 20 73 69 74 20 61 6d 65 74 2c 20 63 6f 6e 73 65 63 74 65 74 75 72 20 61 64 69 70 69 73 63 69 ... > 
<Buffer 65 74 20 71 75 61 6d 20 63 6f 6e 67 75 65 20 6c 6f 62 6f 72 74 69 73 2e 20 50 65 6c 6c 65 6e 74 65 73 71 75 65 20 74 65 6d 70 75 73 20 75 6c 6c 61 6d ... > 
<Buffer 61 2e 20 56 69 76 61 6d 75 73 20 76 69 74 61 65 20 61 6e 74 65 20 6d 65 74 75 73 2e 20 4d 61 75 72 69 73 20 71 75 69 73 20 61 6c 69 71 75 65 74 20 65 ... > 

这表明,在大块收到data事件的数据。只有在end事件中,您才会收到发送的全部数据(如果您在此之前汇总了它)。 Node.js不处理这个问题,这就是为什么你需要第三方模块。

也就是说 - 你不能只得到req.body的请求,因为它根本没有设置

+0

非常感谢你的详细解释。但是,如何直接获取数据。如使用'req.body'获取身体。 – suoyong

+0

我恳求你的另一个答案。当我使用express框架以及需要('body-parse')并将其用作中间件时。但是当我使用表单(

)后,服务器将控制数据。相反,当我使用ajax发布数据时,服务器控制台什么都没有? – suoyong

+0

因为它处理的数据是用AJAX以块形式发送的,而你的工作就是缓冲它。这只是Node工作的方式。使用模块解析POST,不用担心。 – Nevertheless