I am unable to access a file on the server even after exposing it using express

In my current project, I am facing a challenge with storing and allowing end users to download text files dynamically from the browser. While the ideal solution would involve using an object store like MINIO or S3, I am limited to using in-memory storage at the moment. To work around this limitation, I have created a public folder and exposed it using the code snippet below:

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

//setting middleware
app.use(express.static( 'public')); //Serves resources from public folder


var server = app.listen(5000);

It's a straightforward approach. To test whether I can successfully download a file, I placed a file named t.txt inside the public folder and attempted to access it via:

http://localhost:5000/public/t.txt

However, I encountered an issue as illustrated by https://i.stack.imgur.com/WZIcR.png. I'm curious about why I am experiencing this problem and also wonder if my current approach aligns well with the desired scenario and if it is even feasible at all.

Answer №1

When you do not provide a specific path in the app.use() method, your application will display the contents of the directory specified in express.static() at the main root URL. Give this a try:

http://localhost:5000/t.txt

However, if you want the file to be accessed at /public/t.txt, simply define the path like this:

app.use('/public', express.static('public'))

Answer №2

Begin by implementing the code snippet below:

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

This line of code establishes that the static HTML pages are located in the "public" folder within your home directory. It's important to note that "__dirname" refers to the current js file's directory.

Next, access the following URL either through a browser or POSTMAN:

http://localhost:5000/t.txt

You'll notice there's no need to specify

http://localhost:5000/public/t.txt
when referencing the "public" folder because it has already been defined in the app.use line.

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

"The use of Node.js and Express.js in handling HTTP requests and responses

I am intrigued and eager to dive deep into the request and response cycle of backend development. Here's my query: I have a node.js express framework up and running. The app is launched and all functions are primed and ready for requests. app.use(&a ...

NPM encountered an issue while attempting to perform the installation

Having some issues with NPM while trying to install various apps. The errors that I am encountering are outlined below: npm ERR! Darwin 14.5.0 npm ERR! argv "/usr/local/bin/node" "/usr/local/bin/npm" "install" "-g" "ember-cli" npm ERR! node v4.0.0 npm ...

Error encountered when attempting to utilize a variable within an EJS template document

I seem to be encountering some difficulties while attempting to get an EJS template file to recognize a variable that holds the rows from an SQLite3 table query in a related .js file. Whenever I try to access that route by launching the server, I receive a ...

The error message "MQTTJS protocol not found in Node.js"

Currently, I'm working on implementing mqttjs in nodejs and encountered an error when trying to run my main.js file using the command node main.js in the Windows 10 cmd prompt: Error message: C:\Users\Rich\Documents\Code\nod ...

Encountering a problem trying to install the mongodb module for nodejs

I am currently running node version 0.10.28 Whenever I try to run node-gyp install, it gets stuck and I can't proceed with anything else. I'm trying to install the mongodb driver for node.js (npm install mongodb). However, it's asking me t ...

Troubleshooting lpush errors in Node.js with Redis

I'm currently developing a web application using node.js and redis. The goal is to store each incoming request in a redis queue before saving it into a database. However, I keep encountering an error whenever the program executes the lpush command. Be ...

Exploring the depths of mongoose/mongodb with subdocument queries and updates

Data Schema var partSchema = new Schema({_id: Number, completed: Boolean}) var wholeSchema = new Schema({ date: { type: Date, default: Date.now }, author: String, part: partSchema }) var entitySchema = new Schema({ _id: Number, name: String, wholes: [w ...

Having difficulty sharing a photo file to s3 using React and Node's presigned URL

I'm encountering an issue while trying to upload an image file to an AWS S3 bucket. I have set up Node/Express to create a presigned URL for direct uploading from the React frontend to S3. The problem I'm facing is that although I am able to succ ...

Integrating individual front end JavaScript files into an Express.js application

I've been working on a JavaScript file that contains over 200 lines of code for the front end logic of my project. It handles interactions like button clicks, image displays, and more, similar to a game. However, I'm struggling to figure out how ...

Angular ui router - Transitioning from one state to the same state, when no parameters are provided, results in

Check out the Plunker Demo <script> var myapp = angular.module('myapp', ["ui.router"]) myapp.config(function($stateProvider, $urlRouterProvider) { // If there is no matching URL, go to /dashboard $urlRouterProvider. ...

What is the process for constructing a React treebeard project?

As a web programmer who primarily works with browser-based applications, I have found that the once simple world of JavaScript development has become chaotic in recent years. What used to be straightforward now requires installing numerous dependencies wit ...

What is the best way to stream an image file to an upload endpoint using superagent?

/** * Request png image file */ var request = require('superagent') var req = request.get('http://example.com/original/' + id + '.png'); req.end(function(response){ // Now I want to send the response image to another ...

Guide on sending data to MongoDB using Postman

I am currently facing an issue while trying to send data to the MongoDB database using Postman. Despite everything seeming fine, I keep encountering errors. https://i.stack.imgur.com/Gcf5Q.jpg https://i.stack.imgur.com/ntjwu.jpg https://i.stack.imgur.co ...

What alternatives are available to eliminate the need for body-parser?

After successfully installing the express module and body-parser, I realized that I can now utilize express to gather all necessary information from the user without the need for body-parser. How can I safely remove body-parser from my configuration? cli ...

What is the process for releasing an npm package without relying on any babel dependencies?

I am currently working on a npm project called moduleA which I plan to publish to the npm registry. This project utilizes javascript along with webpack4 and babel7. While moduleA functions properly on its own, I encountered some issues with babel when atte ...

Tips for converting the output stream produced by wkhmtlopdf in a Node.js environment to a base64 string without first converting it to a buffer by utilizing AWS Lambda

I have a unique project requirement where I am tasked with converting HTML to PDF using wkhtmltopdf in combination with node.js and AWS Lambda. To accomplish this, we are utilizing the nodejs wrapper for wkhtmltopdf (nodejs-wkhtmltopdf). Up until now, our ...

Tsyringe - Utilizing Dependency Injection with Multiple Constructors

Hey there, how's everyone doing today? I'm venturing into something new and different, stepping slightly away from the usual concept but aiming to accomplish my goal in a more refined manner. Currently, I am utilizing a repository pattern and l ...

npm ci is encountering a problem with conflicting peer dependencies

I'm currently in the process of installing dependencies from a Dockerfile using the command RUN npm ci. However, I keep encountering an error that says Conflicting peer dependencies. Fix the upstream dependency conflict, or retry this command with --f ...

Generate diagrams for Node.js classes

Hello there! I attempted to implement Wavi for a Node.js project in order to create a class diagram. Everything seems to be set up correctly with the path variable and Graphviz installation, but I'm still facing some issues. Can anyone offer any guida ...

"Exploring the capabilities of the Node.js request module

I've been attempting to utilize the request module for sending a post request to another service, but unfortunately, the callback function never seems to fire. Here is my current implementation: request.post( `http://localhost:3002/users/login` ...