Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Refreshing web page causes it to crash

When I refresh the page, the page crashes every time, I have tried replacing ‘end’ with ‘write’, have I just not learnt enough code yet to prevent this? It seems like in the tutorial I am following that this should be working whenever I refresh. Initially starting the webpage is no problem though

const http = require('http');

//connection settings
//port is a end point of communication
const port = 3000;
// hostname: IP associated with any deivce on a network
const hostname = '127.0.0.1';

const respond = (request, response) => {

    //response.setHeader('Content-Type', 'text/plain');
    //writeHead (stațus code, {headers})
    //response.writeHead(200, { 'Content-Type': 'text/html' })
    if (request.url === '/about') {
        response.end("about")
    }

    if (request.url === '/') {
        response.end("home page");

    }
    response.end("error page")
    /*
    socket.on('error', function(e){
        console.log(e);
    });
    was searching up a solution but this^ did not work
*/
};

const url = require('url');



const server = http.createServer(respond);

server.listen(port, hostname, () => { console.log('Server listening on port 3000') })

enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

It’s the response.end("error page"). That’s running unconditionally on every request, even when one of your if statements is true.

Perhaps you meant to do an if...else if...else? This would fix your problem.

if (request.url === '/about') {
  response.end('about');
} else if (request.url === '/') {
  response.end('home page');
} else {
  response.end('error page');
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading