Error in navigating Node.js path

Within my server.js file, I have the following code:

app.use(express.static(__dirname + '/public'));

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

app.get('/report', function(req, res){
    res.sendFile('report.html');
});

When I start the server and visit http://localhost:8000, I can see index.html. However, when I try to access http://localhost:8000/report, I encounter an error stating "path must be absolute or specify root to res.sendFile".

My directory structure looks like this:

public
   - index.html
   - report.html

What could be causing this error?

Answer №1

By default, when requesting just "/", express.static() will serve up the index.html file (you can check this out in the documentation reference). Therefore, the index.html file is being served by the express.static() middleware, not by the app.get('/', ...) route.

Both of your app.get() routes are likely experiencing the same issue. The first one is not executed because the request is already being handled by the express.static() configuration, which is returning the index.html file.

The /report route is not processed by express.static() since the request for report is different from report.html. As a result, the middleware does not handle the request, causing your improperly configured app.get('/report', ...) to be called and resulting in an error.

The following code should resolve these issues:

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

app.use(express.static(__dirname + '/public'));

app.get('/report', function(req, res){
    res.sendFile(__dirname + "/public/report.html");
});

app.listen(8080);

Alternatively, you can utilize the path module and concatenate the pieces with path.join():

var path = require("path");

You can then serve the file using this method:

res.sendFile(path.join(__dirname, 'public', 'report.html'));

In my personal nodejs application example, either of the above options for res.sendFile() work effectively.

Answer №2

To begin, execute the command npm install path

Next, you will need to define the main directory:

let express = require('express');
let app = express();
let path = require('path');

app.use(express.static(__dirname + '/public'));

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

app.get('/report', function(req, res){
    res.sendFile('report.html', { root: path.join(__dirname, './public') });
});

app.listen(8000);

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

Make Connections between Schemas with MongoDB, Express, and Mongoose

I need to establish relationships between my schemas in the "Movie" entity so that I can access information from other entities like: Category Actor Director Studio Right now, I am testing with categories. This is the code I have written: controllers/m ...

Is it possible to retrieve data from the server in Node.js/Vuetify based on a specific time frame?

I'm currently using a node.js server for my vuetify project. Within the server, I am parsing a csv file that contains scheduling and time information. Is there a method in my vuetify project to retrieve data from the csv file based on the current time ...

ExpressJS is encountering difficulties retrieving POST requests

The part of code from my app.js that is relevant to the issue at hand can be seen below: var express = require('express'); var bodyParser = require('body-parser'); var app = express(); app.use(bodyParser.json()); app.use(bodyParser.u ...

Node.js environment that simulates a WAMP setting

Embarking on a journey to learn node.js, I find myself struggling with setting up the basic environment properly. Could someone guide me towards a prebuilt stack akin to WAMP, or provide detailed instructions for creating one? I am specifically interested ...

Having trouble sending and parsing parameters in app.post() with Express.js?

I came across this question on Stack Overflow, but unfortunately, the provided solution does not seem to work for me. In my express.js setup, I have: ... bodyParser = require('body-parser') app.use(bodyParser.urlencoded({ extended: true })); ...

Avoiding resources in Passport.js

Currently, I am developing an API endpoint using expressjs and securing it with passportjs (by utilizing the jwt strategy). The issue I am facing is that if I place the /login endpoint outside of the /api path, everything functions correctly. However, I w ...

Is it a good practice to store all user-related data within the user schema in MongoDB?

Here's an example to make the question clearer. Should I keep this schema structure as is, or would splitting it up be better for performance? It's likely that I'll need to expand on this schema in the future. user: new schema({ key: ty ...

I am facing difficulties accessing my PG database on pSequel and establishing a connection with my Node backend

I recently started working on my first Node.js/Express.js API with a PostgreSQL database. After setting up the database and creating some tables last night, I encountered an issue today where I couldn't connect it to my backend. When trying to access ...

Create a dynamic animation page using Node.js, then seamlessly redirect users to the homepage for a smooth user

Good day everyone! I've decided to change things up with my latest query. I'm currently working on adding a loading page animation that will show for 3 seconds when visiting the '/' route, and then automatically redirect to the home pag ...

Even when the outcome is not what was anticipated, mocha chai still manages to ace the examination

When testing my REST API response with mocha, chai, and express, I set the expected status to 201 but unexpectedly got a passing test result it('janus post', () => { request('https://***') .post('/***') .attach(&a ...

Having trouble with npm installation: "npm error! code ERR_SSL_WRONG_VERSION_NUMBER"

Encountering issues while trying to install modules for my react app. When running npm i, the following warnings and errors are displayed: npm WARN read-shrinkwrap This version of npm is compatible with lockfileVersion@1, but package-lock.json was generate ...

It only takes one second for Mongodb's find() operation to retrieve data

In my mongodb database, I have a collection named "restaurants" that contains only one document. When using mongoose to fetch the data with Model.find({restaurantUid}), it takes approximately 1 second. The restaurant document includes 140 products (foods) ...

Properly encoding strings in Node.js

In my NodeJS code, I am dealing with the following string: '3ª Jornada: Resumen 2' which is meant to be displayed as: '3ª Jornada: Resumen 2' I have attempted to convert it using the decodeURIComponent(escape(myString)) ...

What is the proper way to set up Node modules in a subdirectory?

Is there a recommended approach for generating the node_modules folder in a subfolder? I am currently using Bower to install client-side files under a "client" folder and would like to do the same with NPM for server-side dependencies. For instance: MyApp ...

Implementing basic authentication for an Express REST API

I have a REST API where user data is stored in MongoDB. I am looking to implement basic authentication for my API, but I am facing some challenges. I want to check if a user is authorized on certain paths, such as /update. If the user is authorized, the re ...

Unlocking the Power of CheerioJS for Selecting Table Elements

I am struggling to figure out how to use CheerioJS to parse HTML table values and convert them into a JSON object. Despite my efforts, I have only been able to come up with a convoluted solution that doesn't quite work. My goal is to extract informa ...

What distinguishes the sequence of events when delivering a result versus providing a promise in the .then method?

I've been diving into the world of Promises and I have a question about an example I found on MDN Web Docs which I modified. The original code was a bit surprising, but after some thought, I believe I understood why it behaved that way. The specific ...

Changing the address bar URL with Response.redirect in Node.js is not effective

I am currently using Express JS to build a web application. Within certain GET requests, I am redirecting the user to another page when they click a specific link: a( data-icon='home', data-transition='fade', data-role='button&apo ...

I'm experiencing some issues with AwaitingReactions in Discord.js, it's not working properly on

I'm having trouble with implementing reaction awaiting as per the guide in discord.js. For some reason, it just doesn't seem to work on my end. No matter what I try, when I click the emoji, it doesn't register. I've scoured numerous Sta ...

Having trouble with Jest and supertest tests consistently exceeding the timeout?

Hey there, I'm facing a bit of confusion with an error in my project. Currently, I am developing a Universal React App using Webpack 5 and Express. My goal is to incorporate Jest support by utilizing React-testing-Library for the frontend (which is w ...