catalogue_number catalogue_number - 4 months ago 7
Javascript Question

Can a single node.js server file be used to both serve a HTML page and process POST requests from said page?

I'm completely new to running webservers and their architectures. I'm currently building a web app that has a HTML-based GUI that uses some JavaScript to partially process the user data, then send it as a POST request to the web server.

My question is simple: can the same node.js server be used for serving the HTML webpage as for processing the POST requests, or are two different 'servers' (i.e. two different listeners and ports) needed?

If so, what is the simplest way (I'm happy to use Express.js) My current server file is the following:

var express = require('express'),
serveStatic=require('serve-static'),
mysql = require('mysql');

var app = express();

app.use(serveStatic(__dirname));
var port = 8080;
app.listen(port, function() {
console.log('server listening on port ' + port);
});

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

Answer

Just if else block you need with condition request.method == 'POST':

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

console.dir(req.param);

if (req.method == 'POST') { //-- Here Process POST requests
         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
 {  //!!!----Here process HTML pages
    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);