The res.download() function is not functioning properly when called from within a function, yet it works perfectly when directly called through the API in a browser

I have a button that, when clicked, triggers the downloadFile function which contacts the backend to download a file.

async downloadFile(name) {
    await this.$axios.$get(process.env.API_LINK + '/api/files/' + name)
},
app.get('/api/files/:name', (req, res) => {
    res.download('files/' + req.params.name, function (error) {
      console.log('Error : ', error);
    });
})

Upon clicking the button, the console displays an error as undefined. However, if I access the API directly through the browser (

localhost:9000/api/files/teste.pdf
), the file is downloaded successfully.

The correct file name is being passed to the API when the button is clicked.

Edit (14.01.24, 19h36):

I updated the code based on Express 4.x - API Reference (specifically the err section) and included path.join(). Now, there are no errors displayed. However, nothing happens either - no file downloads or errors reported.

I can still manually download the file using the URL

localhost:9000/api/files/teste.pdf
in the browser, but when trying to initiate the download through a button (which calls the downloadFile() function), nothing occurs.

.get('/files/:name', (req, res) => {
    res.download(path.join(__dirname, '..', 'files', req.params.name),  function (err) {
      if (err) {
        console.log(err);
     }
  });
})

Answer №1

Solved the issue by following the steps outlined in this helpful tutorial.

Essentially, I needed to implement:

downloadFile(name) {
    window.location.href = process.env.API_LINK + '/api/files/' + name
}

Instead of:

async downloadFile(name) {
    await this.$axios.$get(process.env.API_LINK + '/api/files/' + name)
},

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

Encountering a 304 status error in the HTTP GET response after deploying a React app on Netlify

After deploying my react application on Netlify, I used the npm run build command to create the local scripts and manually deployed them in production mode on Netlify. The build scripts were generated on my local machine and then uploaded to the Net ...

Display a badge in the navbar on specific VueJS pages

I have embarked on the journey of creating a single page application using Vue 3, and I've encountered an interesting scenario where I want to display a badge in the navigation bar for specific pages. This is how my setup looks: // App.vue <templat ...

Unable to access parameters from Pug template when using onclick event

I am facing an issue with my pug template test.pug. It contains a button that, when clicked, should call a function using parameters passed to the template from the rendering endpoint. Below is the structure of my template: doctype html html head tit ...

Issue with Mongodb's $and operator functionality not functioning correctly

I am struggling to retrieve data using the $and operator in MongoDB in my Node.js application, and it is not functioning correctly. Here is my code: var brand = req.param('Brand').split(','); brand = '"' + br ...

Potential null object in React/TypeScript

Encountering a persistent error here - while the code functions smoothly in plain react, it consistently throws an error in typescript stating "Object is possibly null". Attempts to resolve with "!" have proved futile. Another error logged reads as follow ...

"Utilizing ng-select with ng-model: A Step-by-Step Guide

Currently, I am working on a code that involves using ng-repeat to loop through options. My goal is to utilize ng-select to choose a value based on a specific condition. However, according to the AngularJS documentation: ngSelected does not interact wit ...

What is the optimal method for storing images on a website built with expressjs and mongodb?

I am currently diving into express, nodejs, and mongodb for a project I'm working on - creating a website for a clothing store. The client will be uploading new images every 2 days, which need to be displayed quickly as thumbnails on the website. User ...

Checking to see if all the users mentioned in the message have been assigned a role

Hello everyone, I'm new to asking questions here so please bear with me. I am trying to retrieve all the users mentioned in a message and check if any of them have a specific role, such as the staff role. Thank you for your help! Edit: Here is the ...

Tips for populating a dictionary with a large datalist of around 2000 items

Currently, I'm facing an issue where the code I'm using takes about 10 seconds to run on Chrome and around 2 minutes on IE11, which is the primary browser it will be used with. for (var key in dict) { if (dict.hasOwnProperty(key)) { ...

Selecting list items using the up and down keys in JavaScript/jQuery

As the search terms dynamically populate a list of items, I am looking for a way to make the list items selectable/focused using the up/down keys and hide the dropdown with ESC key. <form> <div> <div class="field"> & ...

Embracing Micro Front End Development

Currently, I have a legacy AngularJS (Angular 1) app that cannot undergo any major changes at the moment. A new standalone app has been created using a newer stack. The goal is to integrate this new app into the old legacy app without making significant m ...

Attempting to dispatch data from Vue.js event bus

I am attempting to increase the count of quotes by one and also add the text from a textarea to an array. While the text is successfully added to the array, the number of quotes always remains zero. I have tried combining the two actions in one method as w ...

Fade out when the anchor is clicked and fade in the href link

Is it possible to create fade transitions between two HTML documents? I have multiple HTML pages, but for the sake of example, let's use index.html and jobs.html. index.html, jobs.html Both pages have a menu with anchor buttons. What I am aiming to ...

What is the best way to programmatically click on an element within the body of a webpage from an Angular component?

I am running a crisp chat service on my website and I am attempting to interact with the chat box from one of my component's typescript files. The chat box is represented as a div element with the id crisp-client inside the body tag. Can someone plea ...

Switch the visibility of a div tag using Next.js

Script export default function Navigation(){ let displayMenu = false; function toggleMenu() { displayMenu = !displayMenu; } return ( <> <button onClick={toggleMenu}>Toggle Navigation</button> {/*This code sh ...

Rendering a page for a missing resource

Within the App.js file, the routes component is currently only wrapping a portion of the website. However, I would like the NotFound component to be rendered for the entire page if an incorrect URL is entered. Can you please provide guidance on how this ...

Tips for successfully sending a nested function to an HTML button and dropdown menu

I'm working on two main functions - getChart() and fetchData(). The goal is to retrieve chart data and x/y axes information from a database. Within the getChart function, I'd like to incorporate a dropdown menu for displaying different types of c ...

Combine the promises from multiple Promise.all calls by chaining them together using the array returned from

I've embarked on creating my very own blogging platform using node. The code I currently have in place performs the following tasks: It scans through various folders to read `.md` files, where each folder corresponds to a top-level category. The dat ...

Implementing a custom error handler in Express while integrating Sentry

Running an Express server for the backend of a website with Sentry (v5.15.5) successfully implemented has been a great step. However, there is a need to improve the error handling on the backend. Currently, when something goes wrong with a request, the cli ...

The toggle-input component I implemented in React is not providing the desired level of accessibility

Having an accessibility issue with a toggle input while using VoiceOver on a Mac. The problem is that when I turn the toggle off, VoiceOver says it's on, and vice versa. How can I fix this so that VoiceOver accurately states whether the toggle is on o ...