2014-11-05 130 views
0

1)上LOCALMACHINE运行的NodeJS服务器,用于接收POST和服务GET

2)与App作出POST REQ到节点服务器一个设备运行的NodeJS服务器。

3)XAMPP页面发出GET请求以获取发送到节点服务器的设备(从点2)。

希望很清楚。

这是我有,但GET接收未定义。 POST日志key1=value1

var http = require('http'); 
http.createServer(function (req, res) { 

console.log(req.method); 

var txt; 

if(req.method == "POST") { 

    res.writeHead(200, {'Content-Type': 'text/plain'}); 
    res.end('Hello World\n'); 

    var url = require("url"), 
     parsedUrl = url.parse(req.url, false), // true to get query as object 
     queryAsObject = parsedUrl.query; 

    txt = JSON.stringify(queryAsObject); 

    console.log(txt); 

} else { 

    // for GET requests, serve up the contents in 'index.html' 
    res.writeHead(200, {'Content-Type': 'text/html'}); 
    res.end('Hello Worldzz\n'); // I WANT TO PASS txt here. 

    console.log("jaa" + txt); 
} 


}).listen(1337, 'my.ip.here'); 
console.log('Server running at http://my.ip.here:1337/'); 

- 更新。检查

function checkServer() { 
    $.ajax({ 
     type: "GET", 
     url: "http://my.ip.here:1337/", 
     async: false, 
    }).success(function(text) { 
     console.log("res" + text); 
     $("h2").text(text); 
    }); 
} 
+1

服务器工作正常,'txt'没有在代码中定义,所以有什么问题? – SetupX 2014-11-05 15:54:47

+0

我有一个script.js的index.html jquery Ajax GET – bboy 2014-11-05 15:55:07

+0

然后,你期望得到什么,GET请求会收到'Hello Worldzz \ n' – SetupX 2014-11-05 15:56:37

回答

1

这只是一个简单的范围问题。由于您希望所有请求共享相同的txt var,因此您需要在所有请求都可以访问的地方定义txt

var http = require('http'); 
var txt; 
http.createServer(function (req, res) { 

    console.log(req.method); 

    //var txt; 
+0

热潮!加工!谢谢@凯文 – bboy 2014-11-05 16:06:23