skip to Main Content

I was trying to set up a simple register page but while setting a route for the post request of the credentials I keep getting this error


node:_http_outgoing:648
    throw new ERR_HTTP_HEADERS_SENT('set');
    ^

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at new NodeError (node:internal/errors:405:5)
    at ServerResponse.setHeader (node:_http_outgoing:648:11)
    at ServerResponse.header (D:BackendFinallyAWorkingProjectnode_modulesexpresslibresponse.js:794:10)
    at ServerResponse.location (D:BackendFinallyAWorkingProjectnode_modulesexpresslibresponse.js:915:15)
    at ServerResponse.redirect (D:BackendFinallyAWorkingProjectnode_modulesexpresslibresponse.js:953:18)
    at Query.onResult (D:BackendFinallyAWorkingProjectserverTestingRegister.js:76:17)
    at Connection._notifyError (D:BackendFinallyAWorkingProjectnode_modulesmysql2libconnection.js:228:21)
    at Connection._handleFatalError (D:BackendFinallyAWorkingProjectnode_modulesmysql2libconnection.js:183:10)
    at Connection.handlePacket (D:BackendFinallyAWorkingProjectnode_modulesmysql2libconnection.js:488:12)
    at PacketParser.onPacket (D:BackendFinallyAWorkingProjectnode_modulesmysql2libconnection.js:97:12) {
  code: 'ERR_HTTP_HEADERS_SENT'
}

And this is my code:


  //Creating the express app and hosting it locally
const express=require('express');
const app=express();
const bcrypt=require('bcrypt');
const mysql=require('mysql2');
const flash=require('express-flash');
const session=require('express-session');


// Load environment variables from .env file
require('dotenv').config();
const port= process.env.PORT ;
const host= process.env.DB_HOST;
const user= process.env.DB_USER;
const db_name=process.env.DB_NAME;
const pass=process.env.DB_PASSWORD;
const sec=process.env.SECRET_SESSION;


app.listen(port);


////Creating a database connection object
const connection = mysql.createConnection({
    host: host,
    user: user,
    password: pass,
    database: db_name
});
connection.connect();

// Setting up the view engine (ejs)
app.set('view engine', 'ejs');
//setting up middlewares
app.use(session({
    secret: sec, // Replace with a strong secret key
    resave: false,
    saveUninitialized: false
}));
app.use(express.urlencoded({extended: false}));
app.use(flash());

////Routing
app.get('/',(req,res)=>{
    res.render('index.ejs');
});

app.get('/login',(req,res)=>{
    res.render('login.ejs');
});

app.get('/register',(req,res)=>{
    res.render('register.ejs');
});

app.post('/register',(req,res)=>{
    const {name,email,password,cpassword}=req.body;
    if(password!=cpassword){
    req.flash('error', 'Passwords do not match');
    res.redirect('/register');}
    ////Setting a query to check if an email already exist
    else{
    connection.query('select * from users where email=?',[email],(error,results)=>{
        if(error){
            req.flash('error', 'An error occurred');
            res.redirect('/register');        }
        if(results.length> 0 ){
            req.flash('error', 'Email already exists');
            res.redirect('/register');
        }
    });}
    const hashedpassword=bcrypt.hash(password,12);
    connection.query('insert into users values (?,?,?)',[name,email,hashedpassword],(error,results)=>{
        if(error){
            req.flash('error', 'Error accquired,Pls try again in a minute');
            res.redirect('/register');        }
    });
    res.redirect('/login');
});

2

Answers


  1. After res.redirect, the code block continues to be read. So you are trying to return more than one response for the same request. So if you return it after processing the res, the problem will be solved.

    In app.post('/register',()=>{}):

    return res.redirect('/login')
    
    return res.redirect('/register')
    

    You can decide this according to the condition of especially if else statements.

    Login or Signup to reply.
  2. res.redirect('/login'); is sent again despite the res.redirect('/register'); was sent because of your if-else condition logic mistake in the code causing the above error.

            if(error){
                req.flash('error', 'An error occurred');
                res.redirect('/register');
                //In function return keyword is used to return from the current  line of code. 
                return;
            }
            if(results.length> 0 ){
                req.flash('error', 'Email already exists');
                res.redirect('/register');
                return;
            }
    

    syntax :

        let one = (req,res) => {  
          if(){
           //logic
           return;
          }
          else {
           //logic
           return;
         }
         res.redirect('/login');
        }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search