Skip to content

Express GET request not reloading page

I’m trying to send the client the next HTML page (create.html) as a response to a GET request (fired by button) using fetch. I am purposely trying to avoid using a form due to formatting issues and potential future scaling issues. The code registers that the request is sent, received, and is responded to with the file but it simply does not reload the page with it. *res.redirect does also not work. I’ve attached my code bellow. JavaScript:

app.get('/', function(req, res) {
    console.log(`[00]: Get request recieved at '/'`);
    res.sendFile('public/start.html' , { root : __dirname});
})

app.get('/login', function(req, res) {
    console.log(`[01]: Get request recieved at '/login'`);
    res.sendFile('public/login.html' , { root : __dirname});
})
app.get('/create', function(req, res) {
    console.log(`[02]: Get request recieved at '/create'`);
    res.sendFile('public/create.html' , { root : __dirname});
})

HTML:

<html>
    <head>
        <meta charset="utf-8">
        <title>HOME PAGE</title>
    </head>
    <body>
        <h1 id='title'>Welcome User!</h1>
        <h2>Select an option bellow!</h2>
        
        <button id="btnToLogin">Login</button>
        <button id="btnToCreate">Create Account</button>

        <p>-ADMIN PANEL-</p>
        <button id="btnDisplay">Display Database</button>
        <button id="btnTruncate">Truncate Database</button>
        <p id='displayText' >[displayText]: Nothing seems to be here...</p>
        
        <script src="start.js"></script> 
    </body>

</html>

HTML JavaScript:

// Gets elements from start.html
var btnToLogin = document.getElementById('btnToLogin');
var btnToCreate = document.getElementById('btnToCreate');
var btnDisplay = document.getElementById('btnDisplay');
var btnTruncate = document.getElementById('btnTruncate');
var displayText = document.getElementById('displayText');

btnToLogin.addEventListener('click', function() { fetch('/login', { method: 'GET' }) });
btnToCreate.addEventListener('click', function() { fetch('/create', { method: 'GET'}) });

I’ve cut out most of my code, just unnecessary for the problem I believe. Everything is required properly and server is set up. And incase it matters i’ve attached a picture of the file structure. Thanks. File Structure

Answer

Fetch performs and gets the data in background. res.redirect redirects a request. And you are sending the request via fetch. Not address bar. In order to do that, you need to use location.href instead of fetch

btnToLogin.addEventListener('click', function() { location.href = '/login' });
btnToCreate.addEventListener('click', function() { location.href = '/create' });