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

Send the express() app variable between files

Hey everyone, I understand there are many similar posts here, but unfortunately I'm still struggling with my issue. Within my server.js file, I have defined my app variable and implemented some configuration: var app = express(); ... In another fil ...

Arranging input fields for different languages

I recently inherited a product that has been developed using AngularJS, and I have a query related to localization. Within the HTML code, there are two input fields of type 'input-number' - one for entering the number of days and another for spe ...

Guide to setting the first tab as the default tab using Thymeleaf, Css, and Bootstrap

I am currently working on a project where I need to dynamically create tabs based on a list retrieved from my Spring backend using Thymleaf and Bootstrap. While I have managed to successfully create the tabs and content, I am facing an issue where the fi ...

Steps for utilizing express-async-handler

I found some interesting code on a repository, take a look: https://github.com/linnovate/mean/blob/master/server/routes/user.route.js However, there is a part of the code that I'm struggling to comprehend: router.route('/') .post(asy ...

Can you identify the missing piece in my design?

#container { width: 250px; margin: 0 auto; } .group { border: 1px solid grey; margin-bottom: 20px; } .group p { text-align: center; font-family: Helvetica sans-serif; font-size: 25px; color: #2e3d49; } .group img{ wid ...

Ways to showcase the contents of a React JavaScript document, or more specifically, a file designed for React interpretation

After trying multiple solutions, I found a conceptual guide on How to call and form a React.js function from HTML. However, the HTML generated doesn't seem to be calling from the JavaScript file as expected. It appears identical to what is mentioned i ...

Generate with different HTML elements

This is a simple React code snippet: var Greetings = React.createClass({ render: function() { return <div>Greetings {this.props.name}</div>; } }); ReactDOM.render( <Greetings name="World" />, document.getElementB ...

Transform the outcome of Request() into a variable

I'm currently working with the following code snippet: request('http://steamcommunity.com/market/priceoverview/?currency=1&appid=730&market_hash_name=Gamma Case', function (e, r, body){ var req_data = JSON.parse(body); conso ...

Creating routes in Node.js after setting up middleware

Currently tackling a project using node.js and encountering a specific issue. After setting up all routes with express (app.get("..", func)), I find myself stuck with a middleware that catches all requests and redirects to a 404-page. The problem arises w ...

Creating a dynamic multi-select feature in AngularJS with ng-repeat

I'm relatively new to AngularJS and JavaScript, but I've managed to create a functional multi-select list. The ng-model linked to the dropdown is part of a "user" DTO object, specifically a property that stores an array of "groups" the user can j ...

React-hot-loader: The `hot` feature was unable to locate the `name` of the specified `module` that you provided

I've been working on a React project using Webpack 4 and hooks, and I'm attempting to implement live reloading of changes with react-hot-loader, as detailed in this particular tutorial. However, whenever I run npm start, I encounter the followin ...

Displaying only the product slug in the URL, excluding the product ID

My website features a list of classifieds that lead users to the detail page when clicked. I want the URL to only show the slug, like: The issue is that product names may not be unique, causing problems if more than one user wants to add a 'red bag&a ...

Internet Explorer 7 has been selected, a dropdown menu appearing over another dropdown

Hey everyone, I could really use some help with this issue. I'm currently working with chosen.js and I'm having some trouble with dropdowns. Please take a look at this picture for reference: problem with dropdowns Below is the HTML code I'm ...

I'm currently attempting to set up the React JS package, but unfortunately encountering some errors in the process

I'm having trouble installing react as I keep receiving errors. My system has npm version 8.12.1 installed. I attempted to downgrade react, but that didn't resolve the issue. I tried the following steps: Update npm using: npm install npm -g Dow ...

ensured maximum height of a div attached to the bottom

<body style="width: 100%; text-align: center;"> <div style="margin: 0 auto;">container <div style="width: 200px; margin-top: 100px; float: left;"> left </div> <div style="width: 728px; floa ...

Is it possible for the UUIDs generated by the uuid package to be identical?

I am in need of creating unique UIDs for objects that will be stored in a database. To achieve this, I am utilizing the UUID npm package for generating unique identifiers. I have concerns regarding the possibility of duplicate IDs being generated by this p ...

"Encountering errors when attempting to create a course with Active status using a service account through the Google Classroom API

I am utilizing googleapis in order to establish a classroom course using a service account. Everything runs smoothly when I do not specify the status, and the course is created with status: PROVISIONED. However, when I attempt to update the status to ACTI ...

The attempt to convert the value "{ _id: '5d41e769277c0c2ab42d2f8b' }" to an ObjectId was unsuccessful in the "Register" model's "_id" path

Every time I attempt to call findById, an error is thrown, stating that Cast to ObjectId failed for value "{ _id: \' 5d41e769277c0c2ab42d2f8b\' }" at path "_id" for model "Register" I have made multiple changes to my code but still c ...

Having trouble getting tsserver-plugins to function properly in either Atom or VSC

My team and I are on a mission to enhance our Angular 2 templates with code completion, similar to what is showcased in this gif. To achieve this goal, we require: tsserver-plugins coupled with tslint-language-service and @angular/language-service We ...

Material-UI: Eliminating linkOperator functionality in data-grid

Is there a way to completely eliminate the linkOperator UI from the filter panel? I managed to move pagination to the top of the table using Material-UI, but can I achieve the same for the "Operators" menu programmatically? ".MuiDataGridFilterForm-linkOpe ...