I want to make an axios request from vuejs to a node.js server. This request triggers a python script on the server, which creates a file that has to be sent back to the user as a file download.
Edit: The code is actually fine. It's been obviously some server issues. Following I'll paste the code snippets for the sake of completeness.
I have the following prime-vue component to upload files to a server..
<FileUpload name="upFile" url="http://localhost:3000/upload" :multiple="false" @upload="processFile" :maxFileSize="10000000">
This is the function that gets called after the file has been uploaded. If the promise is fulfilled, the returned file is being downloaded. The code is from this post.
axios.get("http://localhost:3000/single-file", {
params: {
filename: event.files[0].name
},
responseType: 'arraybuffer'
})
.then(function (response) {
const url = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', response.config.params.filename.replace('zip', 'docx'));
document.body.appendChild(link);
link.click();
})
In node the file upload is being processed by the /upload route and moves files..
app.post('/upload', type, upload.array(), cors(), jsonParser, (req, res) => {
fs.copyFile(req.file.path, '/home/ubuntu/bot/input/' + req.file.originalname, (err) => {
if (err) throw err;
});
res.send("OK");
});
The /single-file route handles the rest, e.g. calls a python script and returns a file..
app.get('/single-file', type, upload.array(), cors(), jsonParser, (req, res) => {
var filename = req.query.filename;
const spawn = require("child_process").spawn;
const pythonProcess = spawn('python3',["/home/ubuntu/bot/bot.py", filename]);
pythonProcess.on('exit', (code) => {
res.setHeader('Content-type', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document');
res.setHeader('Transfer-Encoding', 'chunked');
res.download('/home/ubuntu/bot/output/' + filename.replace('zip', 'docx'));
});
});
When the child_process reaches the state 'exit' I get the following error..
Error: Can't set headers after they are sent.
The response is sent almost immediately (~2s) after the request has been sent, even though the script runs about 30 seconds.