M
M
Maloy1232015-09-14 15:50:30
JavaScript
Maloy123, 2015-09-14 15:50:30

Web server on Node.js. Why is the response duplicated and no data sent?

Hello.
I'm trying to write a primitive web server, but I'm having a problem.
When requesting, responses are duplicated, for example, joxi.ru/Vrw3yB9F9GLbrX
When working according to the Server Side Events standard, there were also problems - data is not sent. To be more precise, they begin to be sent only after some time, and then if data is sent later, if not, then the "test message" will not be sent.
Below is the code for the web server.

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

http.createServer( function ( request, response ) {
  switch( request.url ) {
    case '/':
      response.writeHead( 200, { 'Content-Type': 'text/html; charset=utf-8' } );
      fs.readFile( 'index.html', function ( error, data ) {
        response.end( data );
      } );
      break;

    case '/js/jquery.js':
      response.writeHead( 200, { 'Content-Type': 'application/javascript; charset=utf-8' } );
      fs.readFile( 'js/jquery.js', function ( error, data ) {
        response.end( data );
      } );
      break;

    case '/js/script.js':
      response.writeHead( 200, { 'Content-Type': 'application/javascript; charset=utf-8' } );
      fs.readFile( 'js/script.js', function ( error, data ) {
        response.end( data );
      } );
      break;

    case '/data':
      response.writeHead( 200, { 'Content-Type': 'text/event-stream' } );
      response.write( 'data: test message\n\n' );
      // setInterval( function () {
      // 	response.write( 'data: '+( new Date ).toLocaleTimeString()+'\n\n' );
      // }, 3000 );
      break;

    default:
      response.writeHead( 404, { 'Content-Type': 'text/plain' } );
      response.end();
      break;
  }
} ).listen( 3000, '127.0.0.1' );

index.html
<!DOCTYPE html>
<html>
  <head>
    <script src="/js/jquery.js"></script>
    <script src="/js/script.js"></script>
    <title>node.js</title>
  </head>
  <body>
  </body>
</html>

js/script.js (commented out)
/*$( function () {
  var sse = new EventSource( '/data' );

  sse.message = function ( e ) {
    console.log( e.data );
  }
} );*/

js/jquery.js v2.1.3
Thanks for your help!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
T
Timur Shemsedinov, 2015-09-14
@MarcusAurelius

On '/data' you don't do response.end(); In general, using switch in this case is bad, you need to do a hash search and readFileSync to do readFile with a callback. Check out a good example here: https://github.com/perfectjs/node-server/blob/mast...

I
Ilnur Ibautllin, 2015-09-15
@ilnuribat

judging by the picture - one file came from the server, the other from the cache
So, there are no duplications here

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question