1

I am new to Node, and I am trying to make it so that when I go to 'localhost:1337/download/open' it renders a webpage, as well as download a file.. I understand that you can only set a header once (that is the error I am getting), but what is the easiest way to both render html AND download a file? Code below:

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

app.get('/download/open', function (req, res) {
    let file = `${__dirname}/downloads/Open Tasks.csv`;
    res.download(file);
    res.send("words");
})

app.listen(1337, function (err) {
    if (err) {
        console.log(err)
        return
    }
    console.log(`App running. listening on: http://localhost:1337`);
});

Error:

Error: Can't set headers after they are sent.

Thank you in advance.

Brandons404
  • 109
  • 1
  • 9

2 Answers2

0

IMO, I would suggest you should do the following to achieve your goal:

  1. render the HTML result for "GET http://localhost:1337/download/open"

  2. In the HTML file /download/open, put AJAX block to invoke download file operation (Download a file by jQuery.Ajax)

    $(document).ready(function(){

    //code to invoke download file....

    });

Kuma C.
  • 66
  • 3
  • I'm sorry, I dont really understand what you're saying.. I am not very familiar with Jquery either and there are a ton of responses in your link, I dont know what "code to invoke download file" would be, based on those. A lot of them seem to make some call to a url, would that url be something I configure in node? Is that where I put res.download? Thank you for your response. – Brandons404 Aug 10 '20 at 02:49
0

I was able to figure out what I was trying to do. Instead of trying to render a whole new page AND download a file, I needed to dedicate a route to just a download through the use of an <a></a> tag.

For instance, if I have a webpage at 'http://localhost:1337' that has a link on it like:

<a href="/download/open">Download Open Tasks</a>

Download Open Tasks

Then in node.js I have a route for 'download/open' like so:

app.get('/download/open', function (req, res) {
    let file = `${__dirname}/downloads/Open Tasks.csv`;
    res.download(file);
})

It will not open a new page (like I thought it needed to) it will just download the file.

Brandons404
  • 109
  • 1
  • 9