title: Download file on ajax success node.js
body: <p>I am building an app using node.js that needs to allow the user to download a .csv file. </p>
  
  <p>The problem - the app does not send a file to the client as an attachment when the user clicks a button. HOWEVER, if the client goes directly to the API link, the file will download. E.g. - if the user goes to <code>localhost:3000/api/exportmetric</code>, the a file will be sent to the client as an attachment. But if that route is hit as an AJAX request, nothing happens.</p>
  
  <p>User flow:</p>
  
  <p>1) User clicks a button</p>
  
  <p>2) App makes AJAX GET request to server</p>
  
  <p>3) Server retrieves data from a database</p>
  
  <p>4) Server parses the data into a .csv file</p>
  
  <p>5) Server sends file back to the client to download as an attachment.</p>
  
  <p>My code:</p>
  
  <p>client.js</p>
  
  <pre><code>$("#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);
          }
      });
  });
  </code></pre>
  
  <p>server.js</p>
  
  <pre><code>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);
      });
  });
  </code></pre>