Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

123
Visualizações
passport.authenticate() isn't redirecting

I have a problem with passport middleware, when I am authenticating a user it doesn't redirect I have no idea what's wrong.

Here is the code and whole project on GitHub:

const express = require("express");
const router = express.Router();
const passport = require("passport");
const genPassword = require("../passwordUtils").genPassword;
const connection = require("../database");
const User = connection.models.User;
// const logRegController = require("../controllers/log-reg-controller");

router.post(
  "/login",
  passport.authenticate("local", {
    successRedirect: "/",
    failureRedirect: "/register",
  })
);

router.post("/register", async (req, res) => {
  const existingUser = await User.findOne({ username: req.body.username });
  if (existingUser) return res.json({ message: "User already exists" });

  const saltHash = genPassword(req.body.password);

  const { salt, hash } = saltHash;

  const newUser = new User({
    username: req.body.username,
    hash: hash,
    salt: salt,
  });

  newUser.save().then((user) => console.log(user));

  res.status(201).json({ message: "All good" });
});

module.exports = router;

https://github.com/Oliwier965/Photo-App/tree/main

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Dear StackOverflow community, this was a challenging battle but I come from it with an answer.

The problem was that I was sending post request using javascript fetch() which is an interface for making AJAX requests. And it is specifically designed to not change your URL. My solution is to send the URL that I want to redirect through res.json() with status 302 and redirect using the frontend. Hope it will help someone I attach the code below.

BACKEND

router.post("/login", function (req, res, next) {
  passport.authenticate("local", function (err, user, info) {
    if (err) {
      return next(err);
    }
    if (!user) {
      return res.status(302).json({ redirectUrl: "/register" });
    }
    req.logIn(user, function (err) {
      if (err) {
        return next(err);
      }
      //If Successful
      return res.status(302).json({ redirectUrl: "/" });
    });
  })(req, res, next);
});

FRONTEND

const login = async function (e) {
  e.preventDefault();
  const username = loginForm.querySelector("#email").value;
  const password = loginForm.querySelector("#password").value;

  const response = await fetch("/login", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      username,
      password,
    }),
  });

  const result = response.json();

  const data = await result;

  const { redirectUrl } = data;

  window.location.href = redirectUrl;
};

about 4 years ago · Juan Pablo Isaza Relatório

0

You can try it with a callback function that redirects you can do it like this according to Docs

router.post('/login', function(req, res, next) {
passport.authenticate('local', function(err, user, info) {
    if (err) { return next(err); }
    if (!user) { return res.redirect('/register'); }
    req.logIn(user, function(err) {
        if (err) { return next(err); }
        //If Successful
        return res.redirect('/');
    });
    })(req, res, next);
});
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda