"Efficiently fetch data with an Express GET request without the

My goal is to send the client the HTML page (create.html) in response to a GET request triggered by a button click using fetch. I am intentionally avoiding the use of a form due to formatting and potential scalability issues. The code acknowledges that the request is sent, received, and responded to with the file, but it does not reload the page with it. Even *res.redirect does not work as expected. Here's the code snippet below. JavaScript:

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

app.get('/login', function(req, res) {
    console.log(`[01]: Get request received at '/login'`);
    res.sendFile('public/login.html' , { root : __dirname});
})
app.get('/create', function(req, res) {
    console.log(`[02]: Get request received 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 below!</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:

// Accesses 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 have omitted most of my code, focusing on the problem at hand. All dependencies are correctly imported and the server is properly configured. Below is a screenshot of the file structure, in case it is relevant. Thank you. File Structure

Answer №1

Fetch is used to perform data retrieval in the background, while res.redirect is used to redirect a request. When sending a request, you use fetch instead of typing the address directly into the browser's address bar. To navigate to a different page programmatically, you can use location.href as shown below:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Modifying the value of an animated status bar using the same class but different section

I need the status bars to work individually for each one. It would be great if the buttons also worked accordingly. I have been trying to access the value of "data-bar" without success (the script is able to process the "data-max"). However, the script see ...

PHP - Variables can only contain text characters

I am in the process of creating a website and I require a specific function. This function is intended to convert the string into plain text only. For example: $string = "Hello world<div width="100000">aaa</div>"; Rendering this as HTML cou ...

How would you go about creating a VueJS component that displays a table with a set number of columns and automatically distributes the cells within them?

Hey there! I'm currently working with a VueJS component that looks like this: <template> <div> <table> <tbody> <tr v-for="(item, index) in items" :key="index"> <t ...

Generating an interactive table using JSON with Angular 5

Can a dynamic table with dynamic columns be created based on a JSON object using Angular 5? If yes, how? The API response includes the following JSON: { "ResponseStatus": true, "ResponseData": [ { "Parent": "Company 1", ...

Validator alert for AMP scripts

I have implemented the amp version for my content management system. Since each article has a different body, some include amp-instagram while others include amp-facebook, and so on. In order to cover all bases, I have added both amp-facebook and amp-inst ...

The store couldn't be located by React-Redux

Working with React, Redux, and Express is causing issues for me. Every time I refresh localhost/courses, an error regarding 'store' not being found pops up. However, If I navigate from localhost -> click to nav course, everything works smoothl ...

Swapping out one variable for another

After tweaking my code a bit, I'm still struggling to get it right. User input: !change Hi var A = "Hello" if (msg.content.includes ('!change')) { A = msg.content.replace('!change ', ''); } msg.send(A); //the change ...

Are tabs best displayed as an overlay?

I've been searching high and low for a tutorial on how to create an overlay with tabs similar to the Google Chrome webstore. If anyone knows of a tutorial or a combination of tutorials that can help me achieve this, please let me know! Link Any guida ...

Connect your Twitter account to your user profile using the Twitter-passport feature

As of now, users can easily log in and sign up for my application without any issues. I recently added a "Link your Twitter user to account" button that redirects the user to '/auth/twitter' upon clicking, initiating the oAuth process through pas ...

Directing BeautifulSoup to a specific <tr> class

I'm currently working on a project where I need BeautifulSoup to extract the numbers located in the "Units Sold" column: from bs4 import BeautifulSoup from urllib import urlopen html = urlopen('http://www.the-numbers.com/home-market/dvd-sales/2 ...

Retrieve the website address from a string of HTML code

I'm struggling to extract the URL from a given String that contains an HTTP response with an HREF tag. I've managed to identify the start of the links, but I need to stop the string as soon as the HREF tag ends. How can I accomplish this? public ...

Retrieve the Checked Value of a Checkbox Using Ajax Post in MVC

Can anyone provide assistance? This is the code I am working with: Index.cshtml <!DOCTYPE html> <html> <head> <title>jQuery With Example</title> @Scripts.Render("~/bundles/jquery") <script type="text/javascri ...

Problem with organizing data by dates

My timers list looks like this: timer 1 => { startDate = 17/01/2019 11PM, endDate = 18/01/2019 9AM } timer 2 => { startDate = 18/01/2019 7AM, endDate = 18/01/2019 1PM } timer 3 => { startDate = 18/01/2019 12PM, endDate = 18/01/2019 10PM } time ...

The React loader fails to function properly when used with nested routes

I'm currently working on my App.js file where I have defined all the routes for my application. I wanted to implement React-Router data loader functionality. import React from 'react' import { Routes, Route, Navigate, RouterProvider, createB ...

Tips for ensuring that the footer remains at the bottom of the content and stays fixed at the bottom of the viewport

In my Django project, I am using Bootstrap 4.5 and I need the footer to be in one of two positions: 1- At the bottom of the content if the content is larger than the view height 2- At the bottom of the viewport if the content is smaller than the view hei ...

Express.js, Passport.js, and cookie-session team up to provide seamless user authentication. However, there seems to be

I am currently utilizing PassportJS and the following code for logout: .get("/logout", async (req, res) => { await req.logout(); req.session = null; await res.clearCookie(process.env.PROJECT_TITLE.toLowerCase()); await res.clearCookie ...

the click event fails to trigger when the id or class is modified

Hey there, I'm new to working with jquery and I've encountered a problem. Here's the code snippet: http://jsfiddle.net/8guzD/ $('#test.off').click(function(){ $(this).removeClass('off').addClass('on'); }) ...

Testing the material-ui toggle component by simulating a click event

Trying to test functionality based on the material-ui toggle component with jest and enzyme has been challenging for me. Even though my generic clickIt function usually works well with other material-ui components, it doesn't seem to trigger the stat ...

What is the correct way to invoke a function from a different file?

Having trouble calling a function from another file in my JS code. I am unable to call a function from another js file. I suspect there is an issue with linking the two files. Code snippet from my first JS file const { response } = require('expre ...

Is it possible to transfer the reactivity of a Vue ref to another ref while reassigning it?

Below is a simplified version of my Vue component: <template> <div @click="loadEvents">{{ loading }}</div> </template> <script setup> import { ref } from 'vue' let loading = ref(false) loadEvents() func ...