0

I want to get data from form and based on that, add data to three tables in mySQL, I use Sequelize to do so, However I don't how to do so, my current idea gives error:

Unhandled rejection Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

My code is like this:

app.post("/device/add", (req, res) => {
    db.Devices.create({
      device_id: req.body.device_id,
      server: req.body.server,
      type: req.body.type
    })
      .then(result => {
        res.json(result);
      })
      .catch(err => {
        throw err;
      });

    db.Modules.create({
      device_id: req.body.device_id,
      device_options: req.body.device_options,,
      sleep_options: req.body.sleep_options
    })
      .then(result => {
        res.json(result);
      })
      .catch(err => {
        throw err;
      });

    db.Tests.create({
      device_id: req.body.device_id,
      gsm_tests: req.body.gsm_tests,
      led_tests: req.body.led_tests,
    })
      .then(result => {
        res.json(result);
      })
      .catch(err => {
        throw err;
      });
  });

can I somehow create it in one response? Or how to make it work

Jacki
  • 632
  • 3
  • 14
  • 26

1 Answers1

0

The problem is that you are trying to send again a response after you have sent one.

For more clarification, refer here

You can use Promise.all() to accumulate the results and then send it in one res.json() call.

const createDevice = db.Devices.create({
      device_id: req.body.device_id,
      server: req.body.server,
      type: req.body.type
    })

const createModules = db.Modules.create({
      device_id: req.body.device_id,
      device_options: req.body.device_options,
      sleep_options: req.body.sleep_options
    })
const createTests = db.Tests.create({
      device_id: req.body.device_id,
      gsm_tests: req.body.gsm_tests,
      led_tests: req.body.led_tests,
    })

Promise
    .all([createDevice , createModules , createTests ])
    .then(result=> {
        res.json({
                 devices: result[0],
                 modules: result[1],
                 test   : result[2]
              });

})
    .catch(err => {
       throw(err);
    });
Siddharth Yadav
  • 383
  • 2
  • 9