0

I got an error every time Im trying to insert data into my MySQL database using the function router from express. It seems like my server try to send a response twice, but I do not know where. Here is the error :

throw err; // Rethrow non-MySQL errors
     ^
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at ServerResponse.setHeader (_http_outgoing.js:526:11)
    at ServerResponse.header (C:\Users\makia\Documents\PERSO\projets\elengi\salon-user\server\node_modules\express\lib\response.js:771:10) 
    at ServerResponse.send (C:\Users\makia\Documents\PERSO\projets\elengi\salon-user\server\node_modules\express\lib\response.js:170:12)   
    at ServerResponse.json (C:\Users\makia\Documents\PERSO\projets\elengi\salon-user\server\node_modules\express\lib\response.js:267:15)   
    at Query.<anonymous> (C:\Users\makia\Documents\PERSO\projets\elengi\salon-user\server\src\bookingClient.js:24:36)
    at Query.<anonymous> (C:\Users\makia\Documents\PERSO\projets\elengi\salon-user\server\node_modules\mysql\lib\Connection.js:526:10)     
    at Query._callback (C:\Users\makia\Documents\PERSO\projets\elengi\salon-user\server\node_modules\mysql\lib\Connection.js:488:16)       
    at Query.Sequence.end (C:\Users\makia\Documents\PERSO\projets\elengi\salon-user\server\node_modules\mysql\lib\protocol\sequences\Sequence.js:83:24)
    at Query.ErrorPacket (C:\Users\makia\Documents\PERSO\projets\elengi\salon-user\server\node_modules\mysql\lib\protocol\sequences\Query.js:92:8)
    at Protocol._parsePacket (C:\Users\makia\Documents\PERSO\projets\elengi\salon-user\server\node_modules\mysql\lib\protocol\Protocol.js:291:23) {
  code: 'ERR_HTTP_HEADERS_SENT'
}

Here is my code:

const express = require('express');

function createRouter(db) {
  const router = express.Router();

  router.post('/bookings/createbookings', (req, res, next) => {
    db.query(
          'insert into booking (idHairdresser,idClient,date,note,status,time,slot,city,address,price) values (?,?,?,?,?,?,?,?,?,?)',
        [req.body.idHairdresser, req.body.idClient, new Date (req.body.date), req.body.note, req.body.status, req.body.time, req.body.slot,req.body.city,req.body.address,req.body.price],
        (error) => {
          if (error) {
             res.status(500).json({status: 'error'});
        } else {
             res.status(200).json({status: 'ok'});
        }
      }
    );
    });

  return router;
}

module.exports = createRouter;

Here is source code where I connect my database, expressjs:

const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const mysql = require('mysql');
const hairdresser = require('./hairdresser');
const bookingHairdresser = require('./bookingHairdresser');
const bookingClient = require('./bookingClient');
const review = require('./review');
const prestation = require('./prestation');
const planning = require('./planning');



const connection = mysql.createConnection({
  host     : 'localhost',
  user     : 'user',
  password : 'password',
  database : 'database'
});

connection.connect();

const port = process.env.PORT || 8080;

const app = express()
  .use(cors())
  .use(bodyParser.json())
  .use(bookingClient(connection))
  .use(hairdresser(connection))
  .use(bookingHairdresser(connection))
  .use(review(connection))
  .use(prestation(connection))
  .use(planning(connection));
  

app.listen(port, () => {
  console.log(`Express server listening on port ${port}`);
});

Here is the code I do on my client side :

  createBookings(
    booking: Booking){
    return this.http.post(`${environment.serverUrl}/bookings/createbookings`, booking);
  }

If you need more information, I can send the details of my source code. Thanks in advance for all your supports :)

Makfe MAKIADI
  • 43
  • 1
  • 5
  • Can't see anything in particular in that code. What other middleware are you using on the app before this is handled? – Matt Oct 27 '20 at 07:51
  • Does this answer your question? [Error: Can't set headers after they are sent to the client](https://stackoverflow.com/questions/7042340/error-cant-set-headers-after-they-are-sent-to-the-client) – Alex Yepes Oct 27 '20 at 07:54
  • Your code is solid. Could you post the code that calls createRouter()? – pspi Oct 27 '20 at 07:54
  • maybe you have an middleware that returns someting? – bill.gates Oct 27 '20 at 07:57

2 Answers2

0

The problem is that in you are sending the response multiple times. Please send details of source code so I can look into it

Akash Shyam
  • 104
  • 9
0

It clearly is a case of Middleware's taking you for a toss.

The error popped up in bookingClient.js:24.

The only possibility could be any router after bookingClient(hairdresser, bookingHairdresser, bookingHairdresser, review, presentation & planning) have a similar route '/bookings/createbookings'.

If yes, you might want to update your app.js as app.use('PATH_PREFIX', bookingClient). Then, the paths inside bookingClient will become 'PATH_PREFIX/bookings/createbookings'.

Satya Kalluri
  • 5,148
  • 4
  • 28
  • 37