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

258
Visualizações
express-session/cors/Axios returns 401 (unauthorized)

UPDATE: it aparently works on firefox, I was using brave. I guess it's blocking the cookie with the session?? I don't know what to do about that.


I'm building an app with Vue, connecting through Axios to an API made with express.

I'm trying to use express-session to manage login sessions and auth. On my localhost it works great, but when I tried to use it from the site hosted on heroku, it breaks. The middleware that checks whether the session has an usuario property blocks the call.

I'm pretty sure it has to do with https instead of http. I tested it on localhost https with some generated credentials and it broke the same way.

The endpoint for login is quite long, but basically checks if the password you gave it is correct, and if it is, it sets req.session.usuario to an object with some user data. After that, when I check again for the session, usuario is not set.

The CORS middleware:

const cors = require("cors");

const whitelist = ["https://localhost:8080", "https://hosted-client.herokuapp.com"];
const corsOptions = {
    credentials: true,
    origin: (origin, callback) => {
        if (whitelist.includes(origin))
            return callback(null, true);

        //callback(new Error("CORS error"));
        callback(null, true);
    },
};

module.exports = cors(corsOptions);

The session middleware:

const Redis        = require("ioredis");
const connectRedis = require("connect-redis");
const session      = require("express-session");

const RedisStore = connectRedis(session);
const redisClient = new Redis(
    process.env.REDIS_PORT,
    process.env.REDIS_HOST,
    {password: process.env.REDIS_PASSWORD}
);

module.exports = session({
    store: new RedisStore({ client: redisClient }),
    secret: process.env.SECRET,
    saveUninitialized: false,
    resave: process.env.STATE_ENV === "production",
    proxy: true,
    cookie: {
        secure: process.env.STATE_ENV === "production",
        httpOnly: true,
        sameSite: "none",
        // maxAge: 1000 * 60 * 30, // 30 minutos
    },
});

A simple test auth middleware:

module.exports = function (req, _, next) {
    if (!req.session || !req.session.usuario) {
        const err = new Error("No se encontró una sesión");
        err.statusCode = 401;

        next(err);
    }
    next();
}

The Axios instance on the client:

require("dotenv").config();
import axios from "axios";

export default axios.create({
    baseURL: process.env.VUE_APP_API,
    headers: {
        "Content-type": "application/json",
    },
    withCredentials: true,
});

I'm not sure if that's enough info, if not let me know.

over 4 years ago · Santiago Trujillo
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