Reputation: 157
I'm trying to do something tricky here, I am uploading a file with multer
successfully into MemoryStorage
. The point is that I need to take the file from memory and send to another server. Here is what I am doing:
var express = require('express');
var router = express.Router();
var path = require('path');
const multer = require('multer');
const FormData = require('form-data');
router.post('/files', upload.single('file'), function (req, res) {
const axios = require('axios');
const url = configuration.dataHub.url + '/api/files';
var config = {
headers: {'x-token': req.session.token, 'Content-Type': 'application/json'}
};
const form = new FormData();
form.append('file', req.file.buffer);
if (req.session.hasOwnProperty('token')) {
axios.post(url, form, config)
.then(response => {
if (response.data.success) {
console.log("Arquivo enviado");
res.send({
success: true,
message: 'Arquivo enviado com sucesso!'
});
} else {
console.log("Arquivo nao enviado");
res.send({
success: false,
message: "Houve um problema ao enviar a ficha, verifique sua conexão ou tente novamente mais tarde."
});
}
})
.catch((error) => {
console.log("N Enviado", error.message);
res.send({
success: false,
message: "Houve um problema ao enviar o arquivo, verifique sua conexão ou tente novamente mais tarde."
});
});
} else {
res.send({
success: false,
session: false,
message: "Sua sessão expirou após 5 minutos sem uso. Faça login novamente!"
});
}
});
Using this code, I am getting the error:
write after end
Any solutions for this?
Upvotes: 1
Views: 4221
Reputation: 157
I changed to request js, doing this way, works fine:
formData = {
file: {
value: file.buffer,
options: {
filename: file.originalname,
contentType: file.mimetype
}
}
};
var options = {
url: url,
headers: {
'x-token': req.session.token
},
formData: formData
};
request.post(options, function optionalCallback(err, httpResponse, body) {
if (err) {
res.send({
success: false,
session: true,
message: 'There is a problem sending the files!'
});
} else {
result = result.concat(JSON.parse(body));
res.send({
success: true,
session: true,
message: 'sucess!',
files: result
});
}
});
Upvotes: 0
Reputation: 15647
Instead of res.send()
try to use res.write()
and use one res.send()
at the end of your code where you think you've finished all processing, and this res.send()
should be followed with a res.end()
Hope this helps!.
Upvotes: 1