I am writing a small app that submits information from a React app to an Express server's "/download" API where it then writes a new file to the local file system and downloads the newly created file on the client side using the Express res.download() in the fs.writeFile() callback.
I've been using a regular html form submit to post the data but due to an increase in complexity I've switched over using Axios and it's no longer working.
The strange thing is only the download on the client side seems to have stopped working. Writing the file works just fine, all the console logging is the same ("File downloaded!" logs below). When I switch back to the form submit it continues to work so the only change is using Axios to send the post request. As far as I'm aware there shouldn't be any difference between the two once the data gets there but I'm hoping someone has greater insight into this than I.
In addition to testing between form and Axios post requests I've also tried changing the content-type of the Axios request to be "x-www-form-urlencoded" from "application/json" thinking that matching up the content type to what the form was sending might be the answer
The below is the relevant code snippets from the app in question:
server.js (Node JS)
app.post('/download', (req, res) => {
console.log("Requst data");
console.log(req.body.html);
fs.writeFile("./dist/test.txt", res.body.test,
(err) => {
if(err) {
return console.log(err);
} else{
console.log("The file was saved!");
}
let file = __dirname + '/text.txt';
/*This is the issue, the file is not downloading client side for the Axios iteration below*/
res.download(file,(err)=>{
if(err){
console.log(err);
} else {
console.log(file);
/*This logs for both View.js iterations below*/
console.log("File downloaded!");
}
});
});
})
App.js (React)
handleSubmit(e){
e.preventDefault();
axios.post(`/download`, {test: "test"})
.then(res => {
console.log("REQUEST SENT");
})
.catch((error) => {
console.log(error);
});
}
render(){
return(
<div>
<View handleSubmit={this.handleSubmit} />
</div>
)
}
View.js (React)
This works:
render(){
return(
<form action="/download" method="post">
<input type="submit">
</form>
)
}
This doesn't initiate the download on the client side, but otherwise works just fine:
render(){
return(
<form onSubmit={this.props.handleSubmit}>
<input type="submit">
</form>
)
}
I'm not getting any error, everything seems to be working properly except the download on the client side.
The expected result is that the file downloads on the client side using Axios but that's not the case.
Update: Bump, not getting any traction on this