var http = require(‘http’);
var server = http.createServer();
var querystring = require(‘querystring’);
var count=0;
var firstPage = function(res){
res.writeHead(200, {’Content-Type’: 'text/html’});
var html = "?json={’interfaceid’:’0x1002’,’mac’:’cat’,’gameid’:’23’,’uid’:’3000’}";
res.end(html);
}
var login = function(req, res) { var info =’’;
req.addListener('data', function(res.){
console.log('\n chunk:'+chunk);
info += chunk;
})
.addListener('end', function(){
info = querystring.parse(info);
console.log('\n System:'+info.interfaceid);
})
}
var requestFunction = function (req, res){
if(count==0){
firstPage(res);
}else{
login(req, res)
}
count++;
}
server.on('request’,requestFunction);
server.listen(1337, “127.0.0.1”);
console.log(‘Server running at http://127.0.0.1:1337/’);
以上部分代码,用post发送了内容为var html = "?json={’interfaceid’:’0x1002’,’mac’:’cat’,’gameid’:’23’,’uid’:’3000’}";的json的数据,可是却不进 req.addListener的方法。导致info 为空~难道不能这么用~如果不能的话,哪怎么用POST解析json的数据呢!
看起来是post的问题, 稍微改动下,然后用命令行跑,第二次就会看到listener working:
curl -H "Accept: application/json" -H "Content-type: application/json" -X POST -d '{"interfaceid":'1002',"mac": "cat","gameid":"23","uid":"3000"}' http://localhost:1337
码:
var http = require('http');
var server = http.createServer();
var querystring = require('querystring');
var count = 0;
var firstPage = function(res) {
res.writeHead(200, {
'Content-Type': 'text/html'
});
var html = "?json={'interfaceid':'0x1002','mac':'cat','gameid':'23','uid':'3000'}";
res.end(html);
}
var login = function(req, res) {
var info = '';
req.addListener('data', function(chunk) {
console.log('\n chunk:' + chunk);
info += chunk;
}).addListener('end', function() {
info = JSON.parse(info)
console.log('\n System:' + info.interfaceid);
res.end()
})
}
var requestFunction = function(req, res) {
if(count == 0) {
firstPage(res);
} else {
login(req, res)
}
count++;
}
server.on('request', requestFunction);
server.listen(1337, "127.0.0.1");
curl 是个command line的指令,用它来post个json到你的server,开个terminal即可。如果你的系统没有curl, 也可用别的方法post, 目的就是试试看 进不进你的 req.addListener, 那是你问的吧?