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') })
>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');
}