2012-08-17 165 views
35

我試圖讓javascript與Node.js服務器進行通信。接受POST請求的Node.js服務器

POST請求(JavaScript)的

var http = new XMLHttpRequest(); 
var params = "text=stuff"; 
http.open("POST", "http://someurl.net:8080", true); 

http.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); 
http.setRequestHeader("Content-length", params.length); 
http.setRequestHeader("Connection", "close"); 

alert(http.onreadystatechange); 
http.onreadystatechange = function() { 
    if (http.readyState == 4 && http.status == 200) { 
    alert(http.responseText); 
    } 
} 

http.send(params); 

眼下的Node.js服務器的代碼如下所示。它用於GET請求之前。我不知道如何使它與POST請求一起工作。

服務器(Node.js的)

var server = http.createServer(function (request, response) { 
    var queryData = url.parse(request.url, true).query; 

    if (queryData.text) { 
    convert('engfemale1', queryData.text, response); 
    response.writeHead(200, { 
     'Content-Type': 'audio/mp3', 
     'Content-Disposition': 'attachment; filename="tts.mp3"' 
    }); 
    } 
    else { 
    response.end('No text to convert.'); 
    } 
}).listen(8080); 

在此先感謝您的幫助。

+1

我相信你必須使用'request'的'data' /'end'事件。這適用於我:http://pastebin.com/6aKv7WHJ。不知道這是否是真正的做法。 – pimvdb 2012-08-17 13:20:05

+0

我認爲javascript POST請求可能有問題。當我嘗試發出請求時,它不會在node.js服務器上接收數據。 – 2012-08-17 13:51:56

+1

雖然我認爲這是節點文件的正確代碼。 javascript是問題 – 2012-08-17 14:05:38

回答

75

以下代碼顯示瞭如何從HTML表單讀取值。由於@ pimvdb說你需要使用request.on('data'...)來捕獲正文的內容。

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

    console.dir(req.param); 

    if (req.method == 'POST') { 
     console.log("POST"); 
     var body = ''; 
     req.on('data', function (data) { 
      body += data; 
      console.log("Partial body: " + body); 
     }); 
     req.on('end', function() { 
      console.log("Body: " + body); 
     }); 
     res.writeHead(200, {'Content-Type': 'text/html'}); 
     res.end('post received'); 
    } 
    else 
    { 
     console.log("GET"); 
     //var html = '<html><body><form method="post" action="http://localhost:3000">Name: <input type="text" name="name" /><input type="submit" value="Submit" /></form></body>'; 
     var html = fs.readFileSync('index.html'); 
     res.writeHead(200, {'Content-Type': 'text/html'}); 
     res.end(html); 
    } 

}); 

port = 3000; 
host = '127.0.0.1'; 
server.listen(port, host); 
console.log('Listening at http://' + host + ':' + port); 

如果你使用類似Express.js那麼就可以簡化爲這樣的事情,因爲快遞需要照顧很多HTTP管道的你:

var express = require('express'); 
var fs = require('fs'); 
var app = express(); 

app.use(express.bodyParser()); 

app.get('/', function(req, res){ 
    console.log('GET /') 
    //var html = '<html><body><form method="post" action="http://localhost:3000">Name: <input type="text" name="name" /><input type="submit" value="Submit" /></form></body>'; 
    var html = fs.readFileSync('index.html'); 
    res.writeHead(200, {'Content-Type': 'text/html'}); 
    res.end(html); 
}); 

app.post('/', function(req, res){ 
    console.log('POST /'); 
    console.dir(req.body); 
    res.writeHead(200, {'Content-Type': 'text/html'}); 
    res.end('thanks'); 
}); 

port = 3000; 
app.listen(port); 
console.log('Listening at http://localhost:' + port) 

在這兩種情況下,我正在讀「 index.html的」,這是與JavaScript的一個非常基本的HTML文件正在使用:在

的NodeJS
<html> 
<body> 
    <form method="post" action="http://localhost:3000"> 
     Name: <input type="text" name="name" /> 
     <input type="submit" value="Submit" /> 
    </form> 

    <script type="text/JavaScript"> 
     console.log('begin'); 
     var http = new XMLHttpRequest(); 
     var params = "text=stuff"; 
     http.open("POST", "http://localhost:3000", true); 

     http.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); 
     //http.setRequestHeader("Content-length", params.length); 
     //http.setRequestHeader("Connection", "close"); 

     http.onreadystatechange = function() { 
      console.log('onreadystatechange'); 
      if (http.readyState == 4 && http.status == 200) { 
       alert(http.responseText); 
      } 
      else { 
       console.log('readyState=' + http.readyState + ', status: ' + http.status); 
      } 
     } 

     console.log('sending...') 
     http.send(params); 
     console.log('end'); 

    </script> 

</body> 
</html> 
+0

我現在遇到的問題是JavaScript甚至無法提出請求。當我嘗試發出請求時,node.js文件不執行任何操作。 – 2012-08-17 14:31:56

+2

這可能是因爲我包含的前面的代碼沒有發送POST請求的任何響應(它只顯示在我們收到POST的服務器上)。我更新了代碼以實際在POST中作出響應,照顧它。我還包括了我用來測試它的HTML(其中包括您的JavaScript代碼) – 2012-08-17 15:09:55

+0

非常感謝這項工作。 – 2012-08-17 15:14:04

4

接收POST和GET請求:

1).Server

var http = require('http'); 
    var server = http.createServer (function(request,response){ 

    response.writeHead(200,{"Content-Type":"text\plain"}); 
    if(request.method == "GET") 
     { 
      response.end("received GET request.") 
     } 
    else if(request.method == "POST") 
     { 
      response.end("received POST request."); 
     } 
    else 
     { 
      response.end("Undefined request ."); 
     } 
}); 

server.listen(8000); 
console.log("Server running on port 8000"); 

2)。客戶端:

var http = require('http'); 

var option = { 
    hostname : "localhost" , 
    port : 8000 , 
    method : "POST", 
    path : "/" 
} 

    var request = http.request(option , function(resp){ 
     resp.on("data",function(chunck){ 
      console.log(chunck.toString()); 
     }) 
    }) 
    request.end();