您已经创建的服务器还好吧,但有两个问题:
- 连接端点。你的AJAX是
POST
,所以你需要正确解析POST
请求(不完全解决你的问题,但你需要区分请求方法)。
- 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
的请求,因为它根本没有设置。
您是否为''/''定义了任何路线? – abdulbarik
@abdulbarik谢谢,我认为http.createServer会收到任何请求。不管路线如何。 – suoyong