2012-08-17 12 views
35

Sto tentando di consentire a javascript di comunicare con un server Node.js.Server Node.js che accetta richieste POST

richiesta 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); 

In questo momento il codice del server Node.js simile a questo. Prima era usato per le richieste GET. Non sono sicuro di come farlo funzionare con le richieste POST.

Server (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); 

Grazie in anticipo per il vostro aiuto.

+1

Dovresti usare gli eventi 'data' /' end' di 'richiesta', credo. Questo funziona per me: http://pastebin.com/6aKv7WHJ. Non sono sicuro che sia il vero modo di farlo, comunque. – pimvdb

+0

Penso che ci potrebbe essere qualcosa di sbagliato con la richiesta POST javascript. Non sto ricevendo dati sul server node.js quando provo a fare una richiesta. –

+1

Anche se penso che sia il codice corretto per il file del nodo. Il javascript è il problema –

risposta

75

Il seguente codice mostra come leggere i valori da un modulo HTML. Come @pimvdb ha detto che devi usare request.on ('data' ...) per catturare il contenuto del corpo.

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); 

Se si usa qualcosa come Express.js allora può essere semplificato a qualcosa di simile in quanto espresso si prende cura di un sacco di l'impianto idraulico HTTP per voi:

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) 

In entrambi i casi sto leggendo " index.html", che è un file molto semplice HTML con il JavaScript che si sta utilizzando:

<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

Il problema che sto avendo ora è che il javascript non può nemmeno fare una richiesta. Quando provo a fare una richiesta il file node.js non fa nulla. –

+2

Ciò potrebbe essere dovuto al fatto che il codice precedente che ho incluso non ha inviato alcuna risposta per la richiesta POST (visualizzato solo sul server che abbiamo ricevuto un POST.) Ho aggiornato il codice per rispondere effettivamente nel POST e ciò richiede cura di esso. Ho anche incluso l'HTML che ho usato per testarlo (che include il tuo codice JavaScript) –

+0

Grazie mille questo funziona. –

4

Ricevere POST e GET richiesta in nodejs:

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). Cliente:

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(); 
Problemi correlati