The error tells me i "Cannot set headers after they are sent to the client"
async function saveFile(file) {
await ipfs.add(file, (err, result) => {
if (err){
console.log(err);
}
console.log(result);
});
}
app.post('/upload', async (req, res) => {
const file = req.files.file;
const fileName = req.body.fileName;
const filePath = 'files/' + fileName;
console.log(file);
const fileHash = saveFile(JSON.stringify(file));
res.send(fileHash);
res.render('pages/upload.ejs', { fileName, fileHash });
});
I'm having trouble finding the documentation of ipfs.add() in the js-ipfs documentation, so the code below is a guess.
When you use await with an async function, you don't generally provide a callback. The value will be returned by await, and errors are turned into exceptions, so I use try/catch around it.
saveFile() needs to return the file hash returned by ipfs.add(), and you need to use await when calling saveFile to get the returned value.
async function saveFile(file) {
try {
let result = await ipfs.add(file);
console.log(result);
return result;
} catch (err) {
console.log(err);
}
}
app.post('/upload', async(req, res) => {
const file = req.files.file;
const fileName = req.body.fileName;
const filePath = 'files/' + fileName;
console.log(file);
const fileHash = await saveFile(JSON.stringify(file));
res.send(fileHash);
res.render('pages/upload.ejs', {
fileName,
fileHash
});
});