ERR_HTTP_HEADERS_SENT - Json Web Tokens in Node.js

0

I'm trying to implement the JSON TOKEN in node.js but I have this error:

  

[ERR_HTTP_HEADERS_SENT]: Can not set headers after they are sent to the client at ServerResponse.setHeader (_http_outgoing.js: 469: 11)

This is the code I have:

router.post('/api/v1/Login', jsonParser, function(req, res){
  if(!req.body)
  return res.sendStatus(400)
  console.log(req.body);

  var UsuarioReg = req.body.user;
  var ContraReg = req.body.pass;

  console.log("User: "+UsuarioReg + " Contraseña: "+ContraReg)


  var request = new sql.Request();

  try{

      request.query("SELECT * FROM dbo.[Client] WHERE username = '"+UsuarioReg+"'AND pass = '"+ContraReg+"'", function (err, recordset) {
        if(err){
        console.log(err); 
        }else{
          if(recordset.rowsAffected > 0){
            res.write(JSON.stringify("Usuario identificado correctamente"))

            console.log("Usuario identificado correctamente")

            const user = {id: 3};
            const token = jwt.sign({ user },'my_secret_key');

            res.json({
              token:token
            });
          }
        }
      })
    }catch(err){
      res.send(JSON.stringify("Error while querying database :- "+err))
      console.log("Error while querying database :- "+err)
    }

});

I do not understand why this error is due. They help me? Thanks !!!

    
asked by java005 18.09.2018 в 00:25
source

1 answer

1

According to you indicate, the error that shows you is because you can not modify the header after sending the data.

I have solved this error by doing the following:

1.- Middleware in Express

app.use((req, res, next) => {

// Dominio que tengan acceso (ej. 'http://example.com')
   res.setHeader('Access-Control-Allow-Origin', '*');

// Metodos de solicitud que deseas permitir
   res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');

// Encabecedados que permites (ej. 'X-Requested-With,content-type')
   res.setHeader('Access-Control-Allow-Headers', '*');

next();
})

2.- Cors (npm module)

const cors = require('cors')
app.use(cors())

By default, it uses the same header as the incoming request. You could change the default configuration, for this I recommend that you review this documentation: link

I hope I helped you

Greetings

    
answered by 26.09.2018 / 10:12
source