Node.js http return html view to client

Introduction

The HTTP module makes a variety of http request-handling methods available to the server.

The http.createServer() method defines a callback function with request and response objects to handle HTTP requests sent to the server from the browser.


var http = require("http"),
  fs = require("fs");

/* Server initalization */
console.log("Loading server config file synchronously.");
var config = JSON.parse(fs.readFileSync("files/config.json"));

//Create server//from w  w  w. ja v  a 2s . c om
console.log("Creating Node.js server.");

var server = http.createServer(function(request, response) {
  /* Handle routing */
  if(request.url === "/") {
    //If no request url is given, assume the index page should be loaded
    request.url += "index.html";
  }
  console.log("Attempting to load a view matching the request url: " + request.url);
  fs.readFile("views" + request.url, function(error, data) {
    if(error) {
      console.log("There was an error loading views" + request.url + ": " + error);
      response.writeHead(404, { "Content-type":"text/html" });
      response.end(fs.readFileSync("views/404.html"));
    } else {
      response.writeHead(200, { "Content-type":"text/html" });
      console.log("Serving up views" + request.url + " content.");
      response.end(data);
    }
  });
});

//Start server (listening for HTTP requests)
/* The server.listen method assigns the server a port and host to listen for HTTP requests */
console.log("Setting server to listen at " + config.host + ":" + config.port);
server.listen(config.port, config.host, function() {
  console.log("Listening at " + config.host + ":" + config.port);
});



PreviousNext

Related