Guide to navigating to a different webpage with Node.js

I am a beginner user of NodeJS and I have a specific request. I need assistance with setting up a page redirect from one page to another upon clicking on a link. Any guidance provided will be greatly appreciated. Here is the code snippet:

app.js

var express = require('express');
var app = express();

app.get('/', function(req,res){
  res.status(200).sendFile(__dirname + '/index.html');
});

app.get('/newPage.html', (req, res) => res.redirect('/newPage.html'))

var server = app.listen(process.env.PORT || '3000', function(){
  console.log('App listening on Port %s', server.address().port);
  console.log('Press Ctrl+C to quit');
});

index.html

<!DOCTYPE html>
<html>
<head>
    <title>NodeJS - HTML/CSS</title>
</head>
<body>
    <h1>NodeJS HTML and CSS Demo</h1>
    <p>
Lorem ipsum dolor sit amet consectetur, adipisicing elit. Maiores saepe quae debitis alias illum, animi sunt iste
    </p>

        <a href= "newPage.html">new page</a>

</body>
</html>

newPage.html

<!DOCTYPE html>
<html>

<head>
    <title>New page</title>
</head>

<body>
    <h1>This is the new page</h1>
</body>

</html>

Answer №1

Don't forget to explore the possibilities:

app.js

var express = require('express');
var app = express();

app.get('/', function(req,res){
  res.status(200).sendFile(__dirname + '/index.html');
});

app.get('/newPage', function(req,res){
  res.status(200).sendFile(__dirname + '/newPage.html');
});

var server = app.listen(process.env.PORT || '3000', function(){
  console.log('App listening on Port %s', server.address().port);
  console.log('Press Ctrl+C to exit');
});

index.html

<!DOCTYPE html>
<html>
<head>
    <title>NodeJS - HTML/CSS</title>
</head>
<body>
    <h1>NodeJS HTML and CSS Demo</h1>
    <p>
Lorem ipsum dolor sit amet consectetur, adipisicing elit. Maiores saepe quae debitis alias illum, animi sunt iste
    </p>

        <a href="/newPage">explore new page</a>

</body>
</html>

If you're aiming for a static website, take a look at express static files or node-static for guidance

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

What is the best way to determine if a child component's property has changed within a method?

The child component is app-google-maps-panel and has 2 properties in the parent component: <div class="col-6"> <app-google-maps-panel [longitude]="longitude" [latitude]="latitude"></app-google-maps-panel> & ...

When adding text to a React Material UI Box, it can sometimes extend beyond the boundaries

I'm currently working on a straightforward React page, but I've encountered an issue right from the start: my text is overflowing the box and I can't figure out why. Could someone take a look at my styles? Here's a picture showing the ...

Exploring object manipulation and generating unique identifiers by combining values - a beginner's guide

After analyzing the provided data, my goal is to come up with a method of combining the IDs and returning an array of their corresponding keys. // example data var data = [ { id: 1, key: 'a' }, { id: 1, key: 'b' }, { id: 2, key ...

An unexpected page transition occurs when attempting to delete a link

I've successfully created an HTML table that dynamically adds rows and provides an option to delete the current row. Each row represents data retrieved from MongoDB, and upon clicking the delete button, I aim to delete the corresponding item from the ...

Maximizing the potential of NPM modules by harnessing the power of the package.json file

Currently, I am working on developing an NPM module for a command-line tool. Upon installation of the package, it is essential to access and read the user's package.json file. While I understand how to read the file syntactically, my main concern lies ...

Nestjs is encountering an issue where the values of a mongoose created object are coming

I've implemented a user registration method where I need to return the email and name of the created object. I'm trying to access them using object.name or object.email, but they keep returning undefined. Interestingly, calling console.log(object ...

A technique for postponing the addition of a class to a div

I am attempting to create a unique type of slider effect. Inside a single div named #slider, I have 9 items displayed in a line. Link to JsFiddle The slider is 1860px wide, but only 620px is visible at any given time due to the parent having an overflow: ...

Create a boundary behind the title on a see-through backdrop

How can I create a design where there is a line to the left and right of a headline? Usually, I would use border-top on the surrounding element and style the headline with some CSS properties like this: h2 { margin-top: -10px; padding: 0 5px; b ...

Preserving color output while executing commands in NodeJS

My Grunt task involves shelling out via node to run "composer install". var done = this.async(); var exec = require('child_process').exec; var composer = exec( 'php bin/composer.phar install', function(error, stdout, stderr) { ...

What is the process for connecting to MongoDB using an SSL certificate with Node.js and the email address [email protected]?

The version of MongoDB shell I am using is v5.0.2 Everything was working fine before updating Mongoose, but now I'm encountering errors with the latest version of Mongoose. This requires me to update both MongoDB and Node. I have successfully set up ...

Streamlined Boilerplate to Kickstart Your Project

Can anyone suggest a well-crafted boilerplate .less file to kickstart a new project? I'm looking for a comprehensive .less file that includes: CSS Resets styles CSS Normalizer styles CSS3 Helpers (box radius, gradients, box shadow, transition) Basic ...

What steps can be taken to verify if a user has the appropriate permissions to execute a database query

Imagine a scenario where a website is used by car dealerships to manage their car inventory. Each dealership has a unique company_id, and staff members have individual staff_id for accessing the system. When a staff member navigates to the page http://sel ...

Display or conceal a div based on the size of the screen using HTML and CSS

Hey there, I recently finished my first React Project and I’m wondering if there’s a way to hide the 'side-menu' section on mobile screens using CSS. Any suggestions? <div className='side-menu'> <SiderComponent /> < ...

Using Wordpress and JavaScript to dynamically hide a button if a product in the online store does not have an SKU

I'm encountering an issue on my Wordpress site where products with variations are not displaying the inner text on a certain element, despite the fact that the text is present when I inspect the element. Here's the code: const makerBtn = document ...

Tips for retaining the original text value even after clicking the submit button

import java.util.Map; import java.util.HashMap; import javax.servlet.ServletRequest; import javax.servlet.http.HttpServletRequest; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org ...

"Finding the Perfect Alignment: How to Center Legends in Firefox

The issue at hand An issue has been identified where the code functions as intended in Chrome, Opera, and IE but fails to work in Firefox: fieldset>legend { display: table; float: none; margin: 0 auto; } <fieldset> <legend>Legend ...

Tips for applying a CSS class with a smooth fade-out effect

In my Angular project, I am working on creating a custom notification component. Here is the template code I have so far: <aside *ngFor="let message of messages "> <div class="notification" style="position:fixed"> {{message.conten ...

Using an npm package in client-side JavaScript

I've been exploring client-side GitHub packages recently and came across developers mentioning that the packages can be downloaded using npm. This confuses me as I thought these were client-side JavaScript packages. They also mentioned something about ...

What is the process for invoking a server-side Java function from HTML with JavaScript?

Can someone help me figure out the best way to invoke a Java method from HTML (I'm working with HTML5) using JavaScript? I attempted using Applets but that approach didn't yield any results. My goal is to extract the value from a drop-down menu i ...

Transform HTML into PDF while maintaining the original letter spacing

We are in need of converting numerous files to enable search and word highlighting functionality in a web browser, as well as server-side indexing for the searchable words. I have previously utilized an online service like (Step 1, Step 2 on linked page) ...