1

I have a button in my reactjs application which when clicked should download a file. I need to send a token with the request to let user download the file. How can I send a token with it? Had it been a ajax, I would have sent the token in header.

This is my code

<div className="btn btn-default obj-export-btn" onClick={this.exportObjectReport.bind(this)}><span className="fa fa-download"></span></div>


exportObjectReport(){

        window.location = url + "get_labels/";
    }

exportObjectReport is to download the file.

I tried using ajax. But file doesn't get download then. Ajax gets success but no download.

exportObjectReport(){
       // window.location = this.props.video_file_selected.file_url + "get_labels/";

        var that = this;
        var existing_face_array = [];
        var settings = {
            "async": true,
            "crossDomain": true,
            "url": url + "get_labels/",
            "method": "GET",
            "headers": {
                Authorization: "Token " + that.props.token_Reducer.token
            },
            success: function (response, textStatus, jQxhr) {
                console.log('export success')
            },
        }

        $.ajax(settings).done((response) => {

        });
    }
EdG
  • 2,243
  • 6
  • 48
  • 103
  • Is there a reason you don't download the file using AJAX? – Nift Apr 03 '18 at 11:56
  • Ajax is not downloading the file. It executes successfully but download doesn't take place. Please see my code update. – EdG Apr 03 '18 at 12:01
  • 1
    Possible duplicate of [Adding http request header to a a href link](https://stackoverflow.com/questions/15835783/adding-http-request-header-to-a-a-href-link) – CBroe Apr 04 '18 at 11:47

2 Answers2

0

You can try and send it as a query param:

exportObjectReport(){

        window.location = url + "get_labels/" + "?token=YOUR_TOKEN";
    }

and then verify it on the server.

It's a very common pattern on various public API's

silicakes
  • 6,364
  • 3
  • 28
  • 39
  • taken from here: https://stackoverflow.com/questions/35236874/setting-custom-request-header-on-a-page-redirect - You can't really pass anything via the headers during a redirect. – silicakes Apr 03 '18 at 12:09
0

Firstly, it is doable to use JQuery with React, but is not recommended as it is two libraries kind of doing the same thing (manipulating the DOM). Instead use a library made specifically for making requests or use XHR requests.

The answer to your question already exists here: https://stackoverflow.com/a/23797348/2668734

The answer contains both an XHR solution and a JQuery solution

Nift
  • 352
  • 4
  • 10