0

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 });
    
});
JackDonMcLovin
  • 137
  • 2
  • 11
  • `saveFile` doesn't return the hash. And if it did, you need to call it with `await saveFile(...)` – Barmar Jun 01 '22 at 23:06
  • If `ipds.add()` returns the hash, you need `return await ipfs.add(...)` – Barmar Jun 01 '22 at 23:07
  • Are you sure that `ipfs.add()` returns a Promise? Functions that return a Promise don't usually take a callback function as an argument. – Barmar Jun 01 '22 at 23:07

1 Answers1

2

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
  });
});
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • I'm getting "Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client" – JackDonMcLovin Jun 01 '22 at 23:44
  • 1
    you can't use both `res.send()` and `res.render()`. See https://stackoverflow.com/questions/30847070/res-send-and-res-render-calls – Barmar Jun 01 '22 at 23:47