My node server is generating a json object/array. I need to send it to the user, but not to display on the browser, but as a file. How do I do it?
I dont think writing it to a file and then using res.sendFile()
would be a right thing to do.
My node server is generating a json object/array. I need to send it to the user, but not to display on the browser, but as a file. How do I do it?
I dont think writing it to a file and then using res.sendFile()
would be a right thing to do.
You just need to add header
Content-Type
as something that browser won't use to display it directly, then content would be downloaded as attachment.If you want to name the download file then you'll have to use header
Content-Disposition
.JSON object can simply be converted to string and sent with above two headers.
Following is the working server code.
application/json-my-attachment
is a made upContent-Type
name, since browser does not recognize it, it will try to download it. Otherwise you can also add standard headerContent-Type: application/octet-stream
.Edit
Regarding your second question, how to send parameters in
POST
request when downloading file, it can be done easily usingHTML Form
.As you're using
AngularJS
, I'm assuming that you don't want your page to refresh by submitting the form. This can be done using anIFrame
. Just update the IFrame'ssrc
attribute with Javascript to file download path.It solves the page refresh problem but we can not send
POST
requestwith body
using just an IFrame.Here we have to use a
combination of Form and IFrame
. HTML Form has an attributetarget
in which we can specify the name of an IFrame. Form can specify the form parameters, action and HTTP method to use. Since the target is an IFrame it won't refresh the current page.Note: Limitation of this method is that you can not send HTTP headers with the form submission though there are some hacks available.
Following is working code. I have used Expressjs as the node server.
HTML
Javascript
NPM Installation
Node Server
** Server output on download button click**