Blank PDF returned while making a POST Request but works fine with GET

Sambhav Sharma picture Sambhav Sharma · Jan 26, 2015 · Viewed 7.2k times · Source

I have a AngularJs frontend and a NodeJS backend. I am trying to build a PDF on NodeJS based on some parameters from AngularJS and return the PDF in response.

The code I am using seems to work fine when I make a GET request from AngularJS, but it returns a blank PDF when I make a POST request. I need to make a POST request since I have to send some specific data.

I am saving the file on disk first and then sending it to the frontend so I can see that the PDF is being generated correctly. It's either not being sent correctly or read correctly at the FrontEnd.

Following is my AngularJS code

var url = {{My Node Server URL}};
            (Note: Works when I make a Get request, without sending post params)
            var $promise = $http.post(encodeURI(url), {
                    responseType: 'arraybuffer',
                    competitors: competitors,
                    channels: channels
            });

            $promise.then(

                function success(response) {


                    var blob = new Blob([response.data], { type : 'application/pdf' });
                    var pdfLink = (window.URL || window.webkitURL).createObjectURL( blob );

                    window.open(
                      pdfLink,
                      '_blank' // <- This is what makes it open in a new window.
                    );

                    cb(pdfLink);

              }, function error(response) {

                --Error Handling--
              }
           )

Following is my NodeJS code

wkhtmltopdf(
            html,
            { 
                output: pdfName
            },
            function (code, signal) {
                fs.readFile(pdfName, function (err, data) {
                    if (err) {res.writeHead(400); res.end("" + err); return;}

                    res.writeHead(
                        200,
                        {
                            "content-type" : "application/pdf",
                            "Content-Disposition": "attachment; filename=Best.pdf "
                        }
                    );
                    res.end(data);
                });     
            }
        );

I have looked into a lot of places and tried almost everything but nothing seems to be working. Any hint/help/suggestion would be appreciated. Kindly ask if I need to provide any more info or details. TIA

Answer

Sambhav Sharma picture Sambhav Sharma · Feb 2, 2015

Got it! I just had to add responseType as arraybuffer as another argument. I think this is self explanatory as to why this worked. So the following code worked!

var $promise = $http.post(encodeURI(url), {
                    competitors: competitors,
                    channels: channels
            },{responseType: 'arraybuffer'});