I’m making a simple express.js aplication, it has a login form that sends a request, and if authenticated redirects to a page in the frontend and attaches a JWT token to the website’s cookies. The JWT token is being generated, the user is being redirected, but no token is being set.
Here’s the server.js:
app.use(cookieParser());
const allowedOrigins = ['http://127.0.0.1:5501', 'http://127.0.0.1:5500']; // Live server ports
app.use(cors({
origin: allowedOrigins,
credentials: true // Permite envio de cookies e outras credenciais
}));
dotenv.config()
app.use(express.json())
app.use(express.urlencoded({ extended: true }))
Here’s the login route:
router.post('/', (req, res) => {
console.log('nnn-----------------------/LOGIN/--------------------------');
const { login, senha } = req.body;
try {
const users = ler_dbJSON();
const conta = users.filter(user => user.senha === senha && user.login === login);
if (conta.length > 0) {
const contaVerificada = conta[0]
const secret = process.env.SECRET;
const token = jwt.sign({ id: contaVerificada.id }, secret, { expiresIn: "7d" });
console.log("Token: ", token)
res.cookie("token", token, {
httpOnly: true,
sameSite: 'lax',
secure: true
});
const responseUrl = contaVerificada.adm === true ? "page1.html" : `pages2.html`;
console.log('-----------------------/LOGIN/--------------------------nnn');
return res.status(200).json({ url: responseUrl });
} else {
return res.status(401).json({ msg: "Login ou senha incorretos." });
}
} catch (err) {
return res.status(500).json({ msg: "Ocorreu um erro ao carregar o banco de dados", erro: err.message });
}
});
Finaly, the request in the front end
axios.post(api_url, {
login: login,
senha: senha
}, { withCredentials: true }
I’ve used postman to test the route, it’s working perfectly. In the frontend it’s parcially working, i’m being redirected as expected to the correct pages, but no cookies are present (tested it by inspecting the page, and using console.log(), both showed a page with no cookies.)