The res.download() function in Express is failing to deliver the accurate URL to the client

When trying to utilize the res.download() method for downloading specific files from a server, there is an issue where triggering the res.download does not redirect the client to the correct URL. The files intended for download are located in a directory set statically.

The relevant backend code snippet is as follows:

app.get("/downloadfile", function(req,res){
    var file = req.query.file;
    var currentpath = req.query.currentpath;
    console.log("SENDING FILE: " + file + " at: " + currentpath);
    //file = file.substring(20, file.length)
    console.log(file);
    console.log(currentpath + "/" + file);
    res.download(currentpath + "/" + file, file);
})

Upon running this section of code, the terminal output is as below:

SENDING FILE: Matthew Haywood CV.pdf at: /media/pi/ELEMENTS B//Matt Haywood/Uni Work
Matthew Haywood CV.pdf
/media/pi/ELEMENTS B//Matt Haywood/Uni Work/Matthew Haywood CV.pdf

The provided path for the res.download function appears accurate based on the terminal output and no errors were observed in the front end code execution.

This Safari route leads to the following outcome when accessed:

https://i.sstatic.net/mlhtx.png

The concern arises as to why res.download directs to /path_to_file/your_file.pdf/ rather than server/path_to_file/your_file.pdf?

Manually visiting the URL results in successful file downloads, however, the issue lies in the res.download() function redirecting to an incorrect URL.

Answer №1

To resolve this issue, simply insert a location header:

res.set({
    'Location': "new-url"
});
res.download(currentpath + "/" + file, file);

Answer №2

After some troubleshooting, I found a solution by including the following code on the client side:

window.location = "http://" + window.location.host + link;

This change was made within the AJAX call.

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

Mongoose population under specific conditions

I'm encountering an issue with Mongoose. My database consists of multiple models: Transaction Wallet User Organization My current task is to fetch Transactions. Each Transaction has a senderWalletId and a receiverWalletId, both linking to a Wallet. ...

Exploring Highcharts Pie Chart with AJAX for Real-time Data Updates

Looking for some guidance with implementing AJAX in my code to make my chart dynamic based on data from the database. Although the code is error-free, the chart is not refreshing automatically. Any help, comments, or suggestions would be greatly appreciate ...

Is it possible to customize the font color of a placeholder in a v-text-field component in Vue?

Recently, I added the following code snippet to my project: <v-text-field hide-details class="search-field" id="name-input" placeholder="Search by name" v-model="search"></v-text-field> I wanted to change the font color of the placeholder tex ...

Issues with Bootstrap tabs loading jQuery and Ajax are preventing the proper functionality

I am currently facing an issue with a tab pane designed using Bootstrap. The problem arises when attempting to load external pages into the tabs through Ajax using a jQuery script. While the ajax script successfully loads the content of the pages, I am en ...

I'm looking to design a navbar similar to the one in the provided link, and I'd like it to appear when scrolling

I'm struggling to figure out how this particular navbar was created. How can I add a navlist for Videos and make the navbar visible upon scrolling? Are there any resources, articles, or hints to help me get started with this? LINK - ...

My Ajax request does not seem to function properly when attempting to transfer data to a different

Take a look at the following code snippet: <div class="category" id="<?php echo $cat->term_id; ?>"><?php echo $cat->cat_name; ?> </div> $(".category").click(function(){ var categ = $(this).attr('id&apos ...

sending a variable from routes.js to my .ejs template

I need help figuring out how to display user information from my database in a template. var aboutUser = connection.query("SELECT about FROM users WHERE username = ?", req.user, function(err, rows) {});` I want to pass this data to the template like so: ...

I am currently experiencing difficulties with react-navigation as I am unable to successfully pass a parameter through a nested navigation stack

Despite attempting all recommended methods to pass a parameter through a nested navigator in react-navigation, I have hit a dead end. Previous solutions and documentations did not yield results, and even chatGPT failed to provide assistance. So now, with h ...

The recently launched AWS Amplify application (serverless) is encountering a 403 Access Denied error

So I've gone ahead and created a brand new serverless (lambda) app using nodejs, expressjs, and ejs on AWS Amplify. After deploying it to the server using auto deployment, I tried accessing my app through the following URL: master.<...>.amplifya ...

What is the process for implementing CORS on a HTTP server designed for a websocket connection, which is operating on the identical port as an Express application?

Currently, I am in the process of setting up a backend using Node and Express. With Express, I have created a simple REST api. In addition to this, I have also set up a websocket.io instance on the same server with the intention of exposing it on the same ...

Oops! A JSON parsing error occurred due to the presence of an unexpected token '}'

I encountered an issue while trying to develop a registration route using passportjs. When sending a request via Postman, I received the following error message: SyntaxError: Unexpected token } in JSON at position 119    at JS ...

The issue of Access-Control-Allow-Origin not functioning properly when using Ajax for a POST request

I am encountering an issue with the header "Access-control-allow-origin" when making a request using the following code: <script type='text/javascript'> function save() { $.ajax( { type: 'POST', ur ...

Exploring the Methods to Monitor Variables in Framework7 Store

Currently, I am in the process of developing my app and have opted to utilize the new built-in store system instead of relying on Vuex. I have a variable that undergoes frequent changes and previously used the following code when working with Vuex: store.w ...

Why does the order of CSS styling impact my design outcome?

Within my CSS file, I have defined the following styles: .myDiv{ float:left; width:100px; height:100px; } .yellow{ background:#faf8c7; } .lightGrey{ background:#f8f8f8; } In my HTML code: <div class="myDiv lightGrey yellow">& ...

Looking for a way to assign customized thumbnails to images in react-responsive-carousel and react-image-magnifiers?

I am currently working on a product viewer using react-responsive-carousel and react-image-magnifiers. Following an example from this GitHub repository, I encountered an issue with mapping custom thumbnails correctly. Although hard-coding the array works f ...

JavaScript is failing to pass the argument value

Whenever I attempt to pass a value on an onclick=function('') function, the value does not seem to get passed correctly while ($row = mysqli_fetch_array($result)) { $id = $row['id']; echo '<a href="#" onclick="DeleteUse ...

Error: Unable to perform 'getComputedStyle' on the 'Window' object: the first parameter must be of type 'Element'

My goal is to create a rotating effect with a center circle containing 5 inner divs. When the device is rotated on the gamma axis, I want the circle div to rotate in accordance with the gamma degree, while the inner divs rotate in the opposite direction to ...

What is preventing me from returning the result of $.ajax, but I can return the result of $http.post?

I am facing an issue with having 2 return statements in my code: return $http.post({ url: CHEAPWATCHER.config.domain + 'api/Authenticate', contentType: 'application/x-www-form-urlencoded; charset=UTF-8', data: data }); re ...

Combining four numbers to calculate a total with the click of a button

I am currently attempting to calculate the sum of 4 entries in 4 separate text fields, and everything appears to be working correctly except that when I click the button, the sum is not being set. For example, if I enter the number 1 in each text input, th ...

The beta version of Angular 2.0 introduces the BrowserDomAdapter for easy access to the DOM

I have a Component in Angular 2.0 that is attempting to utilize the DOM Adapter API from Angular's BrowserDomAdapter documentation. The initialization of this DomAdapter can be found here. However, I am uncertain about whether the Dom Adapter needs t ...