2

(I'm new to stack overflow). I am trying to use req.json() to send json to a request in Express.js. However, I am calling req.json() from an asynchronous function. Therefore, I am receiving the error Error: Can't set headers after they are sent to the client. I read this post but it did not answer my question exactly - for I think that I am getting the error for a different reason than the asker of the question in that that post. So, my question is, is it possible to send data to a req object from an asynchronous function? If so, how is that done? If not, why is it not possible?

Here is some relevant and verifyable code (requested by @whodini9):

app.post("/command", async (req, res, next) => {
    connections[id].exec(line, { // This is the async function
        out: (stdout) => {
            res.json({
                output: stdout
            });
        }
    }).start();
});
Matt Y
  • 21
  • 2
  • 1
    Can you share an example of your code? – whodini9 Jan 14 '19 at 01:44
  • @whodini9 done. – Matt Y Jan 14 '19 at 01:45
  • Does it work if you leave off the `async`? Remember - app.post() is intrinsically asyncronous (your callback will be invoked asynchronously). So why not just `app.post("/command", function(req, res) {...});`? – paulsm4 Jan 14 '19 at 01:51
  • It still does not work when I remove the `async` – Matt Y Jan 14 '19 at 01:54
  • 2
    Your problem most likely stems from unknowingly calling res.json() several times. Could you give some information/context on the whole `connections[id].exec(line, ..)`? – Azami Jan 14 '19 at 01:55
  • If possible I would `await` the value of calling connection.exec.out then res.json that, but obviously this depends on the implementation of this function. This way you know you only set the response one time when the callback resolves. – whodini9 Jan 14 '19 at 01:57
  • @MattY Can you please post the `connections[id].exec()` body? – Sridhar Jan 14 '19 at 04:13

0 Answers0