Node.js http return 404 Page Not Found

Description

Node.js http return 404 Page Not Found


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

console.log("\nStarting node.js server...\n");

var config = JSON.parse(fs.readFileSync("config.json"));
var host = config.host;
var port = config.port;
var server = http.createServer(function(request, response){
  console.log("Received request: " + request.url + "\n");
  fs.readFile("./public" + request.url, function(error, data){
    if(error){//w  w w. jav a2 s  .  c  o m
      response.writeHead(404, {"Content-type":"text/plain"});
      response.end("Page Not Found!");
    } else{
      response.writeHead(200, {"Content-type":"text/html"});
      response.end(data);
    }

  });

});

server.listen(port, host, function(){
  console.log("Listening " + host + ":" + port);
});

fs.watchFile("config.json", function(){
  config = JSON.parse(fs.readFileSync("config.json"));
  host = config.host;
  port = config.port;

  server.close(); // close old server connection

  // reconnect with a new server connection
  server.listen(port, host, function(){
    console.log("Now Listening " + host + ":" + port);
  });
});



PreviousNext

Related