How to send response header after success login using Passport.js

How to send response header after success login using Passport.js

I use react,express.js and MySQL and also express-session and passport.js.

I use react,express.js and MySQL and also express-session and passport.js.

I want to make an authentication using a passport. so far when I check through console.log the data is saved in the session.

the problem is that I want to send data in the form of user information that is successfully logged in and sent to the client with several JSON files.

but i always get this:

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

and

Status Code: 401 Unauthorized

I have been searching for this problem for hours, please help me

here is my code :

Passport config

import keys from './keys';
import db from './conn';
import bcrypt from 'bcryptjs';
var passport = require('passport')
    ,LocalStrategy = require('passport-local').Strategy;

passport.use(new LocalStrategy( function (username, password, done) {

    let queryFindAdmin = 'select * from admin where username = ? ';
    db.query(queryFindAdmin, [username], (err, result) => {

        if (err) return done(err, null);
        if (result.length > 0) {
            let data = result[0];
            bcrypt.compare(password, data.password)
                .then(isMatch=>{
                    if(isMatch){

                        return done(null, data);
                    }else{
                        return done(null, false, { message: 'Incorrect password.' });
                    }
                })
        }

        return done(null, false, { message: 'Incorrect username.' });
    })

}

));

passport.serializeUser(function (user, done) { console.log(user); done(null, user.id); });

passport.deserializeUser(function (id, done) {

let queryFindAdmin = `SELECT * from admin where id = ${id}`;
db.query(queryFindAdmin, (err, result) => {
    if (err) return done(err, null);
    if (result.length > 0) {
        return done(null, result[0]);
    }
})

});

my Auths Routes

import {Router} from 'express';
import * as AuthController from './controller';
import passport from 'passport';
const routes = new Router();
routes.post('/auth/login',
    passport.authenticate('local'),
    function (req, res) {
        return res.status(200).json(req.user);
    });
routes.post('/auth/register',AuthController.registerAdmin);
export default routes;

My Server.js

import express from 'express';
import bodyParser from 'body-parser';
import passport from 'passport';
import connection from './config/conn';
import session from 'express-session';
import csrf from 'csurf'
import cors from 'cors'
import keys from './config/keys';
import uuidv4 from 'uuid/v4';
import authPassport from './config/passport';
import { CategoryRoutes,ProductRoutes,AuthRoutes,TrackRoutes } from './modules';

const app = express();

app.use(session({ genid: function (req) { return uuidv4() // use UUIDs for session IDs }, name: keys.session.name, secret: keys.session.secret, resave: false, saveUninitialized: true, rolling: true, cookie: { secure: false, httpOnly: true, maxAge: keys.session.maxAge, // satu hari, sameSite: true, }

})); app.use(passport.initialize()); app.use(passport.session()); app.use(csrf({ cookie: false })); app.disable('x-powered-by'); app.use((req, res, next) => { res.header('X-XSS-Protection', '1; mode=block'); res.header('X-Frame-Options', 'deny'); res.header('X-Content-Type-Options', 'nosniff'); res.header("Access-Control-Allow-Origin", keys.origin.url); // res.cookie('hammerstout_t',req.csrfToken(),{sameSite:true});

next();

}) app.use(cors({ origin: keys.origin.url })) app.use(bodyParser.urlencoded({ extended: false })); app.use(bodyParser.json());

app.use('/api/', [CategoryRoutes, ProductRoutes, AuthRoutes, TrackRoutes ]);

const port = process.env.PORT || 5000; app.listen(port, (err) => { if(err){ console.log(err); }else{ console.log(Server running on port ! ${port}); }

});


Angular 9 Tutorial: Learn to Build a CRUD Angular App Quickly

What's new in Bootstrap 5 and when Bootstrap 5 release date?

Brave, Chrome, Firefox, Opera or Edge: Which is Better and Faster?

How to Build Progressive Web Apps (PWA) using Angular 9

What is new features in Javascript ES2020 ECMAScript 2020

How to Use Express.js, Node.js and MongoDB.js

In this post, I will show you how to use Express.js, Node.js and MongoDB.js. We will be creating a very simple Node application, that will allow users to input data that they want to store in a MongoDB database. It will also show all items that have been entered into the database.

Secure Node.js, Express.js and PostgreSQL API using Passport.js

The comprehensive step by step tutorial on building secure Node.js, Express.js, Passport.js, and PostgreSQL Restful Web Service

Creating a RESTful Web API with Node.js and Express.js from scratch

In this article, I’ll show you step by step how to create a RESTful Web API with Node.js and Express.js by building a simple and useful Todo API. This article assumes you have basic javascript knowledge and terminal using capabilities.