catalogue_number catalogue_number - 1 year ago 70
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'),
mysql = require('mysql');

var app = express();

var port = 8080;
app.listen(port, function() {
console.log('server listening on port ' + port);
});'/', function(req, res){
console.log('POST /');
res.writeHead(200, {'Content-Type': 'text/html'});

Answer Source

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

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


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


port = 3000;
host = '';
server.listen(port, host);
console.log('Listening at http://' + host + ':' + port);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download