78

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);
starball
  • 20,030
  • 7
  • 43
  • 238
Ostap Hnatyuk
  • 1,116
  • 2
  • 14
  • 20
  • 1
    You'd have to use `data`/`end` events of `request`, I believe. This works for me: http://pastebin.com/6aKv7WHJ. Not sure if that's the real way to do it, though. – pimvdb Aug 17 '12 at 13:20
  • I think there might be something wrong with the javascript POST request. It's not receiving data on the node.js server when I try to make a request. – Ostap Hnatyuk Aug 17 '12 at 13:51
  • 1
    Although I think that's the correct code for the node file. The javascript is the problem – Ostap Hnatyuk Aug 17 '12 at 14:05

2 Answers2

148

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}`)

Guillermo Oramas R.
  • 1,303
  • 2
  • 14
  • 31
Hector Correa
  • 26,290
  • 8
  • 57
  • 73
  • The problem I'm having now though is that the javascript can't even make a request. When I try to make a request the node.js file does nothing. – Ostap Hnatyuk Aug 17 '12 at 14:31
  • 2
    That might have been because the previous code that I included didn't send anything response for the POST request (It only displayed on server that we received a POST.) I've updated the code to actually respond in the POST and that takes care of it. I also included the HTML that I used to test it (which includes your JavaScript code) – Hector Correa Aug 17 '12 at 15:09
  • Where does the (err) check go? As a variable before req & res, then inform user via console.error(err.stack); otherwise a very complete example, I learnt a lot, kudos. – RealDeal_EE'18 Dec 05 '13 at 03:59
  • 3
    I realize this answer is old but I just wanted to point out that BodyParser now has to be installed separately – Philip Kirkbride Oct 28 '16 at 01:15
  • seems weird to have the form action assume localhost, when it could just be / – GoldenNewby Jun 30 '20 at 19:01
15

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();
Masoud Siahkali
  • 5,100
  • 1
  • 29
  • 18