Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js server that accepts POST requests

I'm trying to allow javascript to communicate with a Node.js server.

POST request (web browser)

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

Right now the Node.js server code looks like this. Before it was used for GET requests. I'm not sure how to make it work with POST requests.

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

Thanks in advance for your help.

like image 426
Ostap Hnatyuk Avatar asked Aug 17 '12 13:08

Ostap Hnatyuk


People also ask

How do I accept a POST request in Node?

POST request (web browser) 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.

How do you send a POST request in node JS?

Example code: var request = require('request') var options = { method: 'post', body: postData, // Javascript object json: true, // Use,If you are sending JSON data url: url, headers: { // Specify headers, If any } } request(options, function (err, res, body) { if (err) { console. log('Error :', err) return } console.

Do node JS servers block on HTTP requests?

Your code is non-blocking because it uses non-blocking I/O with the request() function. This means that node. js is free to service other requests while your series of http requests is being fetched.

What HTTP server does Node use?

Node. js uses JavaScript on the server. The task of a web server is to open a file on the server and return the content to the client.


2 Answers

The following code shows how to read values from an HTML form. As @pimvdb said you need to use the request.on('data'...) to capture the contents of the body.

const http = require('http')  const server = http.createServer(function(request, response) {   console.dir(request.param)    if (request.method == 'POST') {     console.log('POST')     var body = ''     request.on('data', function(data) {       body += data       console.log('Partial body: ' + body)     })     request.on('end', function() {       console.log('Body: ' + body)       response.writeHead(200, {'Content-Type': 'text/html'})       response.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>             </html>`     response.writeHead(200, {'Content-Type': 'text/html'})     response.end(html)   } })  const port = 3000 const host = '127.0.0.1' server.listen(port, host) console.log(`Listening at http://${host}:${port}`)   

If you use something like Express.js and Bodyparser then it would look like this since Express will handle the request.body concatenation

var express = require('express') var fs = require('fs') var app = express()  app.use(express.bodyParser())  app.get('/', function(request, response) {   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>     </html>`   response.writeHead(200, {'Content-Type': 'text/html'})   response.end(html) })  app.post('/', function(request, response) {   console.log('POST /')   console.dir(request.body)   response.writeHead(200, {'Content-Type': 'text/html'})   response.end('thanks') })  const port = 3000 app.listen(port) console.log(`Listening at http://localhost:${port}`)  
like image 84
Hector Correa Avatar answered Sep 20 '22 17:09

Hector Correa


Receive POST and GET request 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). Client :

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(); 
like image 38
Masoud Siahkali Avatar answered Sep 23 '22 17:09

Masoud Siahkali