"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

When additional elements follow, the button ceases to function properly in JavaScript

I am working on creating a text-based idle game that involves multiple buttons and text around them. However, I have encountered an issue where the functionality stops working when I try to add text after the "Work" button. The callback function is no lon ...

Tips for choosing a single checkbox from a set of multiple checkboxes in React.js

I iterated through a list of objects to generate table rows, each containing an input tag with the type set as checkbox. const [ isChecked, setIsChecked ] = useState(false); const handleChange = (e) => { setIsChecked(e.target.checked) ...

How can the jQuery click() method be utilized?

Currently working on a web scraping project, I have managed to gather some valuable data. However, I am now faced with the challenge of looping through multiple pages. Update: Using nodeJS for this project Knowing that there are 10 pages in total, I atte ...

JQuery Slider's Hidden Feature: Functioning Perfectly Despite Being Invisible

Having an issue with a jQuery slider on my local HTML page. The sliders are not showing up as intended. I want it to display like this example: http://jsfiddle.net/RwfFH/143/ HTML <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery ...

What is the best way to display the panel during a postback?

I have a group with two radio buttons labeled purchase and expenses. When the purchase radio button is clicked, the panelpurchase will be displayed, and similarly, the panelexpense will show for the expenses radio button. Check out the image of the output ...

What is the best way to incorporate an AJAX GET request into an HTML element?

Currently, I am attempting to execute a JavaScript code that will convert all <a></a> elements found within another element <b></b> (the specific name in the HTML) into links that trigger an HTTP get request. However, the code I hav ...

Sending images from a C# application to a NodeJS Express server using the PUT method through HttpWebRequest

I have a C# code snippet that is successfully working with another NodeJS Express application, the source code of which I do not have access to. However, I want to keep this code unchanged. string filetoupload = @"D:\testvideo.mp4"; HttpWeb ...

The ngOnInit function is not triggered upon instantiation of an Injectable class

What could be causing the ngOnInit() method not to be called upon resolution of an Injectable class? Code import {Injectable, OnInit} from 'angular2/core'; import { RestApiService, RestRequest } from './rest-api.service'; @Injectable ...

express-session creates a fresh session each time it is initiated, but the session is not saved permanently

In my setup, I am using express for the backend running on localhost:8080 For the frontend, I have employed react on localhost:3000 There is no proxy in use; just a simple http://localhost:3000/roster request to http://localhost:8080/ Cross-origin and head ...

Steps for retrieving a Unicode string from PHP using AJAX

In order to retrieve Unicode strings from PHP for my project, I figured that using AJAX would be the most suitable method. $.ajax({ url: './php_page.php', data: 'action=get_sum_of_records&code='+code, ...

Using json_encode with chart.js will not produce the desired result

I am attempting to utilize chart.js (newest version) to generate a pie chart. I have constructed an array that I intend to use as the data input for the chart. This is the PHP code snippet: <?php if($os != null) { $tiposOs = array('Orçamento ...

Sending emails with SMTP in JavaScript using the mailto form

I'm facing a challenge with my form. I am looking for a way to have the Send-email button trigger mailto without opening an email client, instead automatically sending via JavaScript (smtp). I'm not sure if this is achievable or if I'm askin ...

Eliminate a route from the express middleware

My NodeJs App utilizes a middleware for authorization, structured like this: app.use('/api', authorizeMiddleWare, routes); The 'routes' section is where all the specific routes are defined, such as: router.use('/route1', ro ...

What could be causing the Or operator to malfunction within the ng-pattern attribute in AngularJS?

Currently, I am implementing the ng-pattern="/^(([A-Za-z]{0,5}) | ([0-9]{0,10}))$/". However, it seems like the input control is not accepting values such as "asd" or "09", despite my expectation that both should be valid inputs. Do you think the pipe sy ...

The information from the form is not appearing in the req.body

Utilizing the mean.js framework, I have the bodyParser middleware configured as shown below: app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); app.use(methodOverride()); Additionally, I am using formidable to upload imag ...

Is there a way to trigger a function upon the loading of a template in Angular 2?

I'm a newcomer to angular2 and I need to trigger a function when a template loads or initializes. I have experience with achieving this in angular1.x, but I'm struggling to figure out how to do it in angular-2. Here's how I approached it in ...

Executing the executeScript method in Microsoft Edge using Java and WebDriverWould you like a different version?

I'm currently attempting to execute the following code in Microsoft Edge using WebDriver ExpectedCondition<Boolean> jsLoad = driver -> ((JavascriptExecutor) driver).executeScript("return document.readyState").toString().equals(&quo ...

The measurement of a HTML window's entire content height (not just the visible viewport height)

Currently, I am attempting to determine the total height of a webpage's content, not just what is visible. In my efforts, I have managed to achieve some success in FireFox using: document.getElementsByTagName('html')[0].offsetHeight. Howeve ...

Executing asynchronous promises within an asynchronous promise using the .join() method

I am currently utilizing node/express, MySQL, and Bluebird for my project. When handling client requests, I am performing async database operations. After the initial database operation callback, I need to carry out some calculations before executing two ...

Successful PHP submission confirmation

I have implemented a basic PHP script on my website to handle email sending. <?php $headers ="From:<$from>\n"; $headers.="MIME-Version: 1.0\n"; $headers.="Content-type: text/html; charset=iso 8859-1"; mail($to,$su ...