When the last character in the route is a forward slash, the Express server will load the HTML page with CSS and JavaScript. Conversely, if the last route character

On my second html page model.html, I noticed the following issue: When I include a '/' at the end of my route address in the browser like this: http://localhost:3002/home/model/, the correct html page is loaded, but the css/js files do not load.

However, if I omit the '/' at the end of the route address like this: http://localhost:3002/home/model, the correct html page loads along with the css/js files.

Without the '/' at the end, the css/js files successfully load from statics/css/style.css and js/dynamicData.js.

Interestingly, when the '/' is included at the end, I can use ../statics/css/style.css to load the css file and "../js/chartData.js" to load the js file - but then the version without the '/' fails to load the css/js files.

My folder structure:
    js - contains other javascript files
    node_modules
    statics
      css - holds style.css
      image - includes images
      index.html
      model.html
    index.js - initializes express server
    pc_server.js - express server setup

Express code snippet (pc_server.js)

Middleware configuration:

process.chdir(__dirname);
// base = '/home'
app.use(base, express.static(__dirname));

Defined Routes:

const INDEX_PAGE = '/';
const MODEL_PAGE = '/home/model';

function setupRoutes(app) {

  const BASE = app.locals.base;

  app.get(INDEX_PAGE, redirectHome(app));

  // BASE = '/home'
  app.get(BASE, toHomePage(app));
  app.get(MODEL_PAGE, toModelPage(app));

Functions for the routes:

function redirectHome(app) {
  return errorWrap(async function(req, res) {
    try {
      res.redirect(app.locals.base);
    }
    catch (err) {
      console.error(err);
    }
  });
}

function toHomePage(app) {
  return errorWrap(async function(req, res) {
    try {
      res.sendFile(path.join(__dirname+'/statics/index.html'));
    }
    catch (err) {
      console.error(err);
    }
  });
}

function toModelPage(app) {
  return errorWrap(async function(req, res) {
    try {
      res.sendFile(path.join(__dirname+'/statics/model.html'));
    }
    catch (err) {
      console.error(err);
    }
  });
}

The aim is to ensure that the same page loads properly with css/js regardless of whether the route address includes a trailing '/' like http://localhost:3002/home/model/ or not like http://localhost:3002/home/model

Additional question: Why is it that when I type http://localhost:3002/home, my browser automatically adds a trailing '/' making it http://localhost:3002/home/?

Answer №1

the issue at hand

This problem is likely caused by relative links within your website.

  • When using home/model, a relative link like css/style.css will lead to home/css/style.css
  • On the other hand, when using home/model/, the same link will point to home/model/css/style.css

the resolution:

An easy way to resolve this is by adjusting your link tag to:

<link rel="stylesheet" type="text/css" href="../../home/statics/css/style.css">

This updated link goes back to the root directory before navigating to your specific path, ensuring consistency regardless of the user's location.

why does this work?

The ../../ prefix instructs the browser to move up two levels.

With "home/model/" being seen as a directory within home, going two steps upwards brings the browser back to the root level for a fresh start. When on "home/model", it is treated as a file within the home directory, so one step up takes it to the root level where the additional ../ has no effect.

Once at the root level, the browser then accesses "home/statics/css/style.css" and successfully finds the correct file in all scenarios :)

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

Initializing start scripts in the package.json file

When launching my react app locally, I need to execute three commands: cd react-web npm run postinstall export REACT_APP_CUSTOMER_ENVIRONMENT=xxx npm start After running these commands, the application server starts on localhost:3000. For the start script ...

An open port could not be located on the x86_64-conda_cos6-linux-gnu system

Recently delved into learning React and encountered some challenges that I could use assistance with. I am in the midst of developing an application using this code snippet: npx create-react-app project-name Upon creating the application, I ran into issue ...

The webpage is experiencing a glitch as the favicon fails to appear

I am having trouble showing a favicon on my website. I'm currently using IE8 as my browser. In my .aspx page, I have included the following markup: <head runat="server"> <link rel="shortcut icon" href="Images/favicon.ico" /> </head&g ...

Is there a way to interact with a Bootstrap 5 dropdown in React without triggering it to close upon clicking?

I'm currently working on creating a slightly complex navigation bar using Bootstrap 5 and ReactJS. The issue I'm encountering involves the dropdown menu within the nav bar. Whenever I click inside the dropdown, even if it's just non-link te ...

There seems to be a glitch with the Flask flash messaging feature, as

My Flask application includes login and register routes where I aim to display flash messages when username passwords are not matched. Specifically, this issue arises in my index and login routes: @app.route('/') @login_required def index(): ...

I have an HTML table with multiple cells containing inner HTML tables. I have implemented a function along with buttons to filter the main table, excluding the inner tables

My HTML Table is generated from my database, containing information about machines and their status pulled from emails with HTML Tables. Each row has a click option to open/hide the <td> tag showing the original table for more details and better trac ...

Transferring a Variable from Arduino to JavaScript

Is there a simple way to pass an Arduino variable as a JS variable? Let's say we have an integer Arduino variable called sensorData: int sensorData = analogRead(sensorPin); How can we transfer this value to a JavaScript variable? client.println(&quo ...

Converting Data from MySQL and PHP to Excel

Is there a way to export human resource applications stored in my MySQL table as an Excel file? function exportExcel($filename='ExportExcel',$columns=array(),$data=array(),$replaceDotCol=array()){ global $connect; header('Content-Enc ...

Issues with link behavior when using Angular UI-Router

I am just starting to learn AngularJS and I'm trying to figure out how to pass a parameter using anchor tags within the $stateProvider code. I've been attempting to do so, but it doesn't seem to be working. Can someone guide me on the correc ...

Is it feasible to incorporate two distinct images into a single element using CSS layering?

I have a question about setting a background image for a web page using CSS. Currently, I have the following code: body { font-size: 62.5%; /* Resets 1em to 10px */ font-family: Verdana, Arial, Sans-Serif; background-color: #9D5922; color: #000; margin ...

Nginx and Node.js: A Powerful Web Server Combination

I've been searching for the solution for the past couple of days and I can't seem to figure it out. I have a node application that is utilizing socket io, residing in a subdomain which is nested under multiple folders https://my.example.com/node/ ...

The information returned to the callback function in Angular comes back null

In my Node.js application, I have set up an endpoint like this: usersRoute.get('/get', function(req, res) { //If no date was passed in - just use today's date var date = req.query.date || dateFormat(new Date(), 'yyyy-mm-dd&ap ...

Prevent users from downloading images

I'm trying to prevent image downloads by regular users, like so: <div style="background-image: url(img.jpg); background-size: cover; background-repeat: none; "> <img src="wtrmrk.jpg" style=" opacity: 0; " /> </div> If the img.jpg s ...

Why do I need to constantly configure my environment variables when starting Nodemon in Node.js?

Despite having the necessary path in my environment variables, I am encountering an issue when trying to run nodemon directly. The error message 'nodemon' is not recognized as an internal or external command keeps appearing. Upon installing node ...

Problem with the show/hide feature on jQuery. Automatically scrolls to the beginning of the page

On my website, I have successfully implemented two basic Show / Hide links that are working great. Here is the HTML code: <!DOCTYPE html> <html lang="en"> <head profile="http://gmpg.org/xfn/11"> <meta http-equiv="Content-Type" conte ...

Error Encountered in Yarn: The package appears to be missing from your lockfile. Please run an install command to update your resolutions and resolve this issue

Currently, I am exploring how to seamlessly integrate yarn and npm in my project. If I find that yarn is beneficial for my specific scenario, I might transition the entire project to exclusively use yarn. However, I am encountering the following error mes ...

The sequence of data and the final event triggered by http.createServer

const server = http.createServer(async (request, response) => { if (request.method === "POST") { var data = ""; request .on("data", async (chunk) => { console.log("1"); data + ...

Using Gmail in conjunction with Heroku for email delivery

After completing an order in my web app, I want to automatically send a confirmation email. I decided to use Nodemailer as it is a popular npm package for this purpose. I successfully coded the functionality and tested it in my local environment. Howeve ...

Transforming DOM elements into Objects

Here are some values that I have: <input name="Document[0][category]" value="12" type="text"> <input name="Document[0][filename]" value="abca.png" type="text" > I am looking for a way to convert them into an object using JavaScript or jQuer ...

How can data be transmitted to the client using node.js?

I'm curious about how to transfer data from a node.js server to a client. Here is an example of some node.js code - var http = require('http'); var data = "data to send to client"; var server = http.createServer(function (request, respon ...