Download success file ajax node.js

I am creating an application using node.js, which should allow the user to download the CSV file.

Problem - The application does not send the file to the client as an attachment when the user clicks the button. HOWEVER, if the client goes directly to the API link, the file will be downloaded. For example. - if the user goes to localhost:3000/api/exportmetric, the file will be sent to the client as an attachment. But if this route gets as an AJAX request, nothing happens.

User stream:

1) The user presses the button

2) The application makes an AJAX GET request to the server

3) The server retrieves data from the database

4) The server analyzes the data in a CSV file

5) The server sends the file back to the client for download as an attachment.

My code is:

client.js

$("#export_velocity").click(function(e) {
    console.log('export to velocity hit');
    $.ajax({
        url: 'http://localhost:3001/api/exportmetric',
        type: 'GET',
        success: function(response) {
            console.log(response);
        },
        error: function(a, b, c) {
            console.log(a);
            console.log(b);
            console.log(c);
        }
    });
});

server.js

router.get('/api/exportmetric', function(req, res) {
    console.log('export metric hit');
    var fields = ['first_name', 'last_name', 'age'];
    var fieldNames = ['First Name', 'Last Name', 'Age??'];
    var people = [
      {
        "first_name": "George",
        "last_name": "Lopez",
        "age": "31"
      }, {
        "first_name": "John",
        "last_name": "Doe",
        "age": "15"
      }, {
        "first_name": "Jenna",
        "last_name": "Grassley",
        "age": "44"
      }
    ];

    json2csv({ data: people, fields: fields, fieldNames: fieldNames }, function(err, csv) {
      res.setHeader('Content-disposition', 'attachment; filename=file.csv');
      res.set('Content-Type', 'text/csv');
      console.log(csv)
      res.status(200).send(csv);
    });
});
+5
2

.

1. window.location

window.location URL .

window.location = '/path/to/download?arg=1';

window.open('/path/to/download', '_self');

2.

HTML5 download . ( ) URL. DOM, .

var link = document.createElement('a');
link.href = '/path/to/download';
link.download = 'local_filename.csv';
var e = document.createEvent('MouseEvents');
e.initEvent('click', true, true);
link.dispatchEvent(e);

, , .

, js - http://pixelscommander.com/polygon/downloadjs/#.VrGw3vkrKHv

downloadFile('/path/to/download');

, , , URL-, URL- , .

, , URL -, , POST.

$.ajax({
    type: 'POST',
    url: '/download/path/generator',
    data: {'arg': 1, 'params': 'foo'},
    success: function(data, textStatus, request) {
        var download_id = data['id'];
        // Could also use the link-click method.
        window.location = '/path/to/download?id=' + download_id;
    }
});
+9

, , :

1 - DOM

2 - , ( )

3 -

4 - DOM

JS

  $("#buybtn").click(function(){
    url = "localhost:8080/";
    // we create a form
    var form = document.createElement("form");
    // set the method to Post
    form.setAttribute("method", "post");
    // we set the action to be performed
    form.setAttribute("action", url + "api2");

    // the following variables contains the data to send
    params = {
        name : "name",
        age : "age"
    };

    // we iterate over the available fields in params
    // and set the data as if we are manually filling the form
    for(var key in params) {
        if(params.hasOwnProperty(key)) {
            var hiddenField = document.createElement("input");
            hiddenField.setAttribute("type", "hidden");
            hiddenField.setAttribute("name", key);
            hiddenField.setAttribute("value", params[key]);

            // we insert each element in the form
            form.appendChild(hiddenField);
        }
    }

    // we append the form to the DOM
    document.body.appendChild(form);
    // we submit the form
    form.submit();
    // we delete the created elements
    document.body.removeChild(form);
  });

: JavaScript

, !

0

Source: https://habr.com/ru/post/1627060/


All Articles