Answer the question
In order to leave comments, you need to log in
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' );
<!DOCTYPE html>
<html>
<head>
<script src="/js/jquery.js"></script>
<script src="/js/script.js"></script>
<title>node.js</title>
</head>
<body>
</body>
</html>
/*$( function () {
var sse = new EventSource( '/data' );
sse.message = function ( e ) {
console.log( e.data );
}
} );*/
Answer the question
In order to leave comments, you need to log in
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...
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 questionAsk a Question
731 491 924 answers to any question