2014-11-05 68 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

相關問題