سؤال

I am new to nodejs. I have been trying to write a simple webserver and render html pages. I do not want to use Express or other frameworks at this stage as I am trying to look under the hood.

My problem is this: on loading the page for the first time after starting the server, it loads the default value of response. After that on every alternate loading, it shows Default Page (404 Not Found) and the correct HTML.

Here is the server log on first load (when showing 'default' as response):

  • request for url / received
  • About to route for request /
  • this is the home page
  • content-type text/html
  • FILE READING FINISHED ...

On refreshing, server log is exactly same, but the actual page is displayed.

On further refreshing, I get the 404 Not Found, which is the default case of my router. Server Log is again same.

Here is the server.js code:

var http = require('http');
var url = require('url');

function start(route){
   function onRequest(request, response){
     var pathname = url.parse(request.url).pathname;
     console.log('request for url '+pathname+' received');
     resp = route(pathname);
     console.log('content-type '+resp['ctype']);
     response.writeHead(200, {'Content-Type':resp['ctype']});
     response.write(resp['file'].toString());
     response.end();
    }
   http.createServer(onRequest).listen(8888);
   console.log('Server Has Started');
  };
exports.start = start;

Here is the router code:

var fs = require('fs'),
    datafile={'file':'default', 'ctype':'text/html'};

function read_html(filename){
   fs.readFile(filename, 'utf-8', function(err, data){
      if (err){console.log(err);}
      else {datafile['file'] = data;console.log('FILE READING FINISHED ...\n');}
   }); 
}

function route(pathname){
  console.log('About to route for request '+ pathname);
  switch(pathname){
  case '/': 
     console.log('this is the home page');
     read_html('./index.html');
     datafile['ctype']='text/html';
  break;
  case '/features':
     console.log('this is the FEATURES page');
     read_html('./features.html');
     datafile['ctype']='text/html';
  break;
  case '/css/root.css':
     console.log('this is the CSS');
     read_html('./css/root.css');
     datafile['ctype']='text/css'; 
  break;
  default:
     datafile['file'] = '404 Not Found\n';
     datafile['ctype']='text/html';
     console.log('404 NOT FOUND');
  break;
}
return datafile;
}

Aplogies for the unoptimized code.

هل كانت مفيدة؟

المحلول

I don't know if this is the core of your problem, but this is just wrong. I made some comments to you code, I hope this helps:

function read_html(filename){
    // STEP 1
    fs.readFile(filename, 'utf-8', function(err, data) {
        // STEP 10, you can absolutly not say what
        // happens since you called read_html
        if (err){
            console.log(err);
        }
        else {
            datafile['file'] = data;
            console.log('FILE READING FINISHED ...\n');
        }
    }); 
    // STEP 2, we'll exit the function
}

Try to read more about the async concept and how data is handled in node.js.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top