Node.js server that accepts POST requests

154,315

Solution 1

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

Solution 2

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();
Share:
154,315
Ostap Hnatyuk
Author by

Ostap Hnatyuk

Updated on March 24, 2021

Comments

  • Ostap Hnatyuk
    Ostap Hnatyuk about 3 years

    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.

  • Ostap Hnatyuk
    Ostap Hnatyuk over 11 years
    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.
  • Hector Correa
    Hector Correa over 11 years
    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)
  • RealDeal_EE'18
    RealDeal_EE'18 over 10 years
    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.
  • Philip Kirkbride
    Philip Kirkbride over 7 years
    I realize this answer is old but I just wanted to point out that BodyParser now has to be installed separately
  • GoldenNewby
    GoldenNewby almost 4 years
    seems weird to have the form action assume localhost, when it could just be /