Nuxt-edge serverMiddleware route ignored (Error 404) when deployed - node.js

I'm trying to deplay an SSR nuxt-legacy-edge project on a firebase Hosting.
Every things work fine in dev mode (npm run dev).
I'm using serverMiddleware /api defined in nuxtconfig.js
serverMiddleware: [
bodyParser.json(),
session({
secret: 'amdskfmdlkfdklfndfmdfndsmfndfnejnjheheuewytwgssa',
resave: true,
saveUninitialized: false,
cookie: { maxAge: (20 * 60 * 1000), secure: false }
}),
//{ path: '/api', handler: '~/api/index.js' },
'~/api'
]
and my /api/index.js is
const express = require('express')
const bodyParser = require('body-parser');
const router = express.Router()
const app = express();
app.use(express.static(path.join(__dirname, 'public')));
app.use(bodyParser.json({ limit: '50mb' }));
app.use(bodyParser.urlencoded({ extended: false }));
router.use((req, res, next) => {
Object.setPrototypeOf(req, app.request)
Object.setPrototypeOf(res, app.response)
req.res = res
res.req = req
next()
})
router.post('/confirmlogin', (req, res) => {
console.log('[API] - LOGIN POST', req.body.role)
req.session.userId = req.body.uid
req.session.role = req.body.role
req.session.token = req.body.token
req.session.profile=req.body.profile
res.cookie('access_token', req.body.token, {
maxAge: 3600000,
httpOnly: true
}) /* 1 hour */
return res.json({
status: 'success'
})
})
router.post('/confirmlogout', (req, res) => {
console.log('[API] - LOGOUT POST')
delete req.session.userId
delete req.session.role
delete req.session.token
delete req.session.profile
res.clearCookie('access_token');
return res.json({
status: 'success'
})
})
app.use('/', router);
module.exports = {
path: '/api',
handler: router
}
The firebase functions is defined as:
const functions = require('firebase-functions');
const { Nuxt } = require('nuxt-legacy-edge');
var express =require("express");
var app=express();
const config = {
dev: false,
buildDir: '.nuxt',
};
const nuxt = new Nuxt(config);
exports.webaffitto = functions.https.onRequest((req, res) => nuxt.render(req, res));
As shown in route api/confirmlogin and api/confirmlogout works fine in dev mode but if put in production using command
firebase serve --only functions,hosting or
using
firebase deploy
seem those routes are missing and I obtain a 404 (non found).
Help is appreciated.

Related

Server not functioning in mern heroku deployment

I have a semi successful deployment to heroku but the calls to the server are saying CONNECTION REFUSED and I can't figure it out.
I can hit the route and it returns correctly in postman but not in production
Below is the services file (the ones with /api in front are the ones being called)enter image description here
`import http from "../utils/http-common";
class CountriesService {
getAll() {
return http.get("/api/country");
}
getAllCountries() {
return http.get("/country/getAll");
}
getScroll(skip) {
return http.get(`/country?skip=${skip}`);
}
get(id) {
return http.get(`/country/${id}`);
}
create(countryForm) {
return http.post("/country/new", countryForm);
}
edit(id, values) {
return http.put(`/country/${id}`, values);
}
delete(id) {
return http.delete(`/country/${id}`);
}
}
export const getPostsPage = async (pageParam = 1, options = {}) => {
const response = await http.get(`/api/country?_page=${pageParam}`, options)
return response.data
}
export default new CountriesService();
`
This is the http-common
import axios from "axios";
var url;
process.env.REACT_APP_NODE_ENV === "production"
? (url = "")
: (url = "http://localhost:5000/");
export default axios.create({
baseURL: `${url}`,
headers: {
'Content-Type': 'application/json',
},
withCredentials: true,
});
this is the server file on the backend with a proxy from the frontend to localhost 5000
const path = require('path');
require("dotenv").config();
const express = require("express");
const app = express();
const mongoose = require("mongoose");
const cors = require("cors");
var morgan = require("morgan");
const MongoDBStore = require('connect-mongo');
const mongoSanitize = require('express-mongo-sanitize');
const helmet = require('helmet');
// Models
const User = require("./models/user.js");
// Passport Config
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const flash = require("connect-flash");
const session = require("express-session");
const cookieParser = require("cookie-parser");
// const { MongoClient } = require("mongodb");
const BodyParser = require("body-parser");
const { storage } = require("./imageupload/cloudinary");
const userAuthRoute = require("./routes/user.js");
const reviewRoute = require("./routes/review.js");
const countryRoute = require("./routes/country.js");
const cityRoute = require("./routes/city.js");
const activityRoute = require("./routes/activity.js");
const restaurantRoute = require("./routes/restaurant.js");
const dishesRoute = require('./routes/dishes.js');
const outdoorsRoute = require('./routes/outdoors.js');
const apiRoutes = require("./routes/api.js");
const cityReviewRoute = require("./routes/cityReviews.js");
const foodRoute = require('./routes/food.js');
const landmarkRoute = require('./routes/landmark.js');
const searchRoute = require('./routes/search.js');
const contactRoute = require('./routes/contact.js');
const db_url = process.env.DB_URL;
const PORT = process.env.PORT || 5000;
const secret = process.env.SESSION_SECRET;
// const client = new MongoClient(process.env.DB_URL);
const corsOptions = {
origin: [
"http://localhost:3000",
"http://localhost:5000",
"https://geopilot.herokuapp.com",],
credentials: true,
optionSuccessStatus:200,
};
app.use(cors(corsOptions));
app.use(express.json());
app.use(mongoSanitize({ replaceWith: "_" }));
app.use(BodyParser.json());
app.use(express.urlencoded({ extended: true }));
app.use(morgan("tiny"));
// app.use(cookieParser());
mongoose
.connect(db_url)
.then(() => {
console.log("database connection established successfully");
})
.catch((error) => console.log("this is the error", error));
const store = MongoDBStore.create({
mongoUrl: process.env.DB_URL,
ttl: 24 * 60 * 60 * 365, // 1 year
autoRemove: 'native',
crypto: {
secret,
},
});
store.on('error', function(error) {
console.log('SESSION STORE ERROR:', error);
});
// Session Settings
const sessionOptions = {
name: "geopilot_session",
secret: secret,
store: store,
resave: false,
saveUninitialized: false,
cookie: {
samesite: false,
// httpOnly: true,
// secure: true,
expires: Date.now() + 1000 * 60 * 60 * 24 * 365,
maxAge: 1000 * 60 * 60 * 24 * 365,
},
};
// app.set('trust proxy', 1) // trust first proxy
// Session Setup
app.use(session(sessionOptions));
// Helmet Setup
// app.use(helmet())
// Passport Middleware
app.use(passport.initialize());
app.use(passport.session());
passport.use(new LocalStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
// Routes
app.use("/api/country/:countryId/reviews", reviewRoute);
app.use("/api/country", countryRoute);
app.use('/api/city', cityRoute);
app.use('/api/city/:cityId/reviews', cityReviewRoute);
app.use('/api/activity', activityRoute);
app.use('/api/restaurant', restaurantRoute);
app.use('/api/restaurant/:restaurantId/reviews', reviewRoute);
app.use('/api/landmark', landmarkRoute);
app.use('/api/landmark/:landmarkId/reviews', reviewRoute);
app.use('/api/food', foodRoute);
app.use('/api/dishes', dishesRoute);
app.use('/api/outdoor', outdoorsRoute);
app.use('/api/search', searchRoute);
app.use('/api/user', userAuthRoute);
app.use('/api/contact', contactRoute);
// ----------- Deployment -----------
__dirname = path.resolve();
if (process.env.NODE_ENV === "production") {
app.use(express.static(path.join(__dirname, "../client/build")));
app.get("*", (req, res) => {
res.sendFile(path.resolve(__dirname, "../client", "build", "index.html"));
});
}
// ----------- Deployment -----------
app.get("*", () => {
res.send("PAGE NOT FOUND");
});
I tried requesting in postman which works.
I tried changing things in the package.json to help proxy or run server.
I tried to switch endpoints and change CORS policy but it won't work.
For anyone seeing this and is stuck, I changed http-common baseUrl to match my website url (not localhost) and then had to do "npm run build" to make it actually implement the changes.

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

My express app:
const https = require("https");
const http = require("http");
const path = require("path");
const express = require("express");
const cookieParser = require("cookie-parser");
const dotenv = require("dotenv");
const cors = require("cors");
const helmet = require("helmet");
const logger = require("morgan");
const compression = require("compression");
const session = require("express-session");
const pgSession = require("connect-pg-simple")(session);
const api = require("../server/routes");
const pool = require("../config/database");
/** ====== DotENV configuration */
dotenv.config({ path: require("find-config")(".env") });
const configurations = {
production: { ssl: true, port: process.env.PORT, hostname: "" },
development: {
ssl: false,
port: process.env.PORT,
hostname: process.env.STAGE_HOSTNAME,
},
};
const environment = process.env.NODE_ENV || "development";
const config = configurations[environment];
const {
responseHandlerMiddleware,
sessionChecker,
} = require("../server/middlewares");
const app = express();
var credentials = {
// key: fs.readFileSync("/etc/letsencrypt/live/myresorts.in/privkey.pem"),
// cert: fs.readFileSync("/etc/letsencrypt/live/myresorts.in/fullchain.pem"),
};
let server = config.ssl
? https.createServer(credentials, app)
: http.createServer(app);
app.use(cors());
app.options("*", cors());
app.use(helmet());
app.use(compression());
app.use(logger("dev"));
app.use(express.json({ limit: "20mb" }));
app.use(express.urlencoded({ extended: true }));
app.use(cookieParser());
app.set("trust proxy", 1);
app.use(
session({
store: new pgSession({
pool,
tableName: "session",
}),
name: "user_sid",
secret: process.env.SESSION_SECRET,
resave: true,
cookie: { secure: false, maxAge: 60000 * 5 },
saveUninitialized: true,
})
);
app.use((req, res, next) => {
if (req.session.user && req.cookies.user_sid) {
res.redirect("/dashboard");
}
return next();
});
app.get("/", sessionChecker, (req, res) => {
res.redirect("/login");
});
app.set("views", path.resolve(__dirname, "../views"));
app.set("view engine", "ejs");
app.use(express.static("../public"));
app.use("/", sessionChecker, api);
// app.use(responseHandlerMiddleware);
app.route("/login").get(sessionChecker, (req, res) => {
res.render("pages/login");
});
app.route("/register").get(sessionChecker, (req, res) => {
res.render("pages/register");
});
app.route("/dashboard").get(sessionChecker, (req, res) => {
if (req.session.user && req.cookies.user_sid) {
res.render("pages/dashboard");
} else {
res.redirect("/login");
}
});
module.exports = server;
Session handler middleware:
const sessionChecker = (req, res, next) => {
console.log("sesson ---------", req.session);
console.log("cookies ---------", JSON.stringify(req.cookies));
if (req.session.user && req.cookies.user_sid) {
res.redirect("/dashboard");
} else {
return next();
}
};
Every time I trying to to do a signup, this error keeps popping up multiple times:
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at new NodeError (node:internal/errors:372:5)
at ServerResponse.setHeader (node:_http_outgoing:576:11)
at ServerResponse.header (/home/deep/Node_API/node_modules/express/lib/response.js:794:10)
at ServerResponse.location (/home/deep/Node_API/node_modules/express/lib/response.js:915:15)
at ServerResponse.redirect (/home/deep/Node_API/node_modules/express/lib/response.js:953:18)
at sessionChecker (/home/deep/Node_API/server/middlewares/session.middleware.js:5:13)
at Layer.handle [as handle_request] (/home/deep/Node_API/node_modules/express/lib/router/layer.js:95:5)
at trim_prefix (/home/deep/Node_API/node_modules/express/lib/router/index.js:328:13)
at /home/deep/Node_API/node_modules/express/lib/router/index.js:286:9
at Function.process_params (/home/deep/Node_API/node_modules/express/lib/router/index.js:346:12)
I'm trying to make a session management app using express-session. It should be able to preserve the session and if the session exists it should redirect to the dashboard else should redirect to the login page.
UPDATE:
As robert suggested in the comments, the issue was here:
app.use((req, res, next) => {
if (req.session.user && req.cookies.user_sid) {
res.redirect("/dashboard");
}
return next();
});
I changed it to:
else {
return next();
}
The error is fixed, but it is still not getting redirected to the dashboard after registering a user. Instead, gets called in the following manner multiple times:
GET /dashboard 302 246.426 ms - 64
GET /dashboard 302 247.005 ms - 64
GET /dashboard 302 245.620 ms - 64
GET /dashboard 302 247.940 ms - 64
GET /dashboard 302 246.114 ms - 64
I checked that this doesn't even get called:
app.route("/dashboard").get(sessionChecker, (req, res) => {
if (req.session.user && req.cookies.user_sid) {
res.render("pages/dashboard");
} else {
res.redirect("/login");
}
});
My registerUser controller:
const registerUser = catchAsync(async (req, res, next) => {
const { email, password } = req.body;
const user = await pool.query("select * from find_user_by_email($1)", [
email,
]);
if (user.rowCount) {
res.error = "User already exists";
return next(500);
}
const saltHash = generatePassword(password);
const response = await pool.query("select * from create_user($1, $2, $3)", [
email,
saltHash.salt,
saltHash.hash,
]);
if (response.rowCount) {
req.session.user = { email: response.rows[0].create_user };
res.redirect("/dashboard");
} else {
res.redirect("/register");
}
});
UPDATE(FIX):
It turns out redirects shouldn't be used when we are rendering template files. I replaced all res.redirect with res.render.

I cant access the req.user from passport outside of my routes folder. MERN stack redux node.js

I am trying to access the req.user that passport creates when doing a google o auth strategy. I can access the req.user in the routes file below, but when I try to access it in my userController file it is showing up as undefined.
Why is user accessible in routes file but not userController?
googleAuthRoutes.js:
const passport = require('passport');
const requireLogin = require('../middlewares/requireLogin')
const cors = require('cors');
const axios = require('axios');
const Template = require('../models/Template');
const corsOptions ={
origin: true,
credentials:true, //access-control-allow-credentials:true
optionSuccessStatus:200
}
module.exports = app => {
app.get('/auth/google',
passport.authenticate('google', {
scope: ['profile', 'email']
}));
app.get(
'/auth/google/callback',
passport.authenticate('google'),
(req, res) => {
res.redirect('/dashboard');
}
);
app.post('/templates/create', async (req, res) => {
const { template, body } = req.body
console.log(req.user)
const newTemplate = new Template({
template: template,
body: body,
_user: req.user.id
})
try {
await newTemplate.save()
return res.status(200).json({
message: "Successfully saved template"
})
} catch (err) {
return console.log(err)
}
});
app.get('/api/logout', cors(), (req, res) => {
req.logout();
res.redirect('http://localhost:3000');
});
app.get('/api/current_user', (req, res) => {
res.send(req.user);
})
}
when I call the res.send(req.user) here above it sends the user no problem
But it is undefined with the /templates/create route middleware.
the console.log(req.user) is coming back as undefined??
index.js:
const express = require('express');
const cors = require('cors')
const mongoose = require('mongoose');
const cookieSession = require('cookie-session');
const passport = require('passport');
const keys = require('./config/keys');
const bodyParser = require('body-parser')
require("dotenv").config();
require('./models/GoogleUserModel'); // the user model must be placed before this services passport// this must be ran after requiring model bcuz this needs the model. ORDER
require('./models/UserModel');
require('./services/passport');
const corsOptions ={
origin:'http://localhost:3000',
credentials: true, //access-control-allow-credentials:true
optionSuccessStatus:200
}
const app = express();
app.use(cors(corsOptions))
mongoose.connect(keys.mongoURI, {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true
})
mongoose.connection.on('error', () => {
throw new Error (`unable to connect to database: ${keys.mongoURI}`)
});
app.use(bodyParser.json())
app.use(express.urlencoded( { extended: true }))
app.use(
cookieSession({
maxAge: 30 * 24 * 60 * 60 * 1000,
keys: [keys.cookieKey]
})
)
app.use(passport.initialize());
app.use(passport.session());
require('./routes/userRoutes')(app);
require('./routes/googleAuthRoutes')(app);
require('./routes/messageRoutes')(app);
app.use((err, req, res, next) => {
if (err.name === 'UnauthorizedError') {
res.status(401).json({"error" : err.name + ": " + err.message})
} else if (err) {
res.status(400).json({"error" : err.name + ": " + err.message})
console.log(err)
}
})
const PORT = process.env.PORT || 5000;
app.listen(PORT);
Again, Why is the req.user available in the app.get to /api/current_user but available in a post request to /templates/create?
Im trying to add the user.id to the schema when it saves so i can retrieve each template by the user.id and not show everyone everybody elses templates lol

Openlitespeed Session Timeout after 1 min idle with Nextjs App

Hello Stackoverflow Community.
So I am encountering a very weird problem when hosting my nextjs powered by express with openlitespeed. Everything works great in production, except one thing - the authentification of sessions. The user is saved in the cookies correctly and it works if you are not idle for more than a minute on the page you are on, but if you are idle for more than a minute, then the request is not authenticated anymore even though the cookie is still there.
I am using redis for my cookie store, and everything works in local testing, where openlitespeed is not present. The authentification I am using is passportjs with express-session. Have any of you encountered this problem, and if so, how did you solve it?
I have tried disabling the cache module, set all timeouts to a higher value or disabling them, use different memorystores and more, but no luck. Here is the server.js file, however, I do not believe it has something to do with the code itself, but rather the config of openlitespeed:
const express = require('express')
const next = require('next')
const passport = require('passport');
const redis = require('redis')
const session = require('express-session')
const {v4: uuidv4} = require('uuid');
const path = require('path');
const log = require('./logger')
let RedisStore = require('connect-redis')(session)
let redisClient = redis.createClient()
const port = parseInt(process.env.PORT, 10) || 3000
const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()
app.prepare().then(() => {
const server = express()
//Json parsing
server.use(express.json());
server.use(express.urlencoded({extended: true}));
if (dev){
//Express session
server.use(session({
store: new RedisStore({ client: redisClient }),
genid: function() {
return uuidv4()},
secret: uuidv4(),
resave: false,
saveUninitialized: false,
cookie: {
secure: false,
maxAge: 86400000
}
}))
}
else{
//Express session
server.use(session({
store: new RedisStore({ client: redisClient }),
genid: function() {
return uuidv4()},
secret: uuidv4(),
proxy: true,
resave: false,
saveUninitialized: false,
cookie: {
secure: true,
maxAge: 86400000
}
}))
}
//Passport auth
server.use(passport.initialize());
server.use(passport.session());
//Import of the passport config
const initializePassport = require('./passport-config');
initializePassport(passport);
//Login route
server.post('/login', passport.authenticate('login'), (req, res) => {
res.send({message: 'Successful login', login: true})
});
const passportLogout = function (req, res, next) {
req.logout()
next()
}
//Logout route
server.get('/logout', passportLogout, (req, res) => {
req.session.destroy();
res.redirect('/login');
});
//Import registrerings route. Pga. brugen af route i stedet for app kan vi bruge denne middleware med en anden underside, hvis vi f.eks. ville gøre så admins også kunne lave brugere.
const registerRoute = require('./routes/register-user');
server.use('/register', registerRoute);
//User routes hvor login er required. Rendering. Skal stå under called til initializepassport, ellers kan den ikke finde ud af at den er authenticated via passport, og auth.js returnerer dig derfor til login
const usersRoutes = require('./routes/user/user-routes');
server.use(usersRoutes);
//Admin routes til rendering
const adminRoutes = require('./routes/admin/admin-routes');
server.use(adminRoutes);
const indexRoutes = require('./routes/index-routes');
server.use(indexRoutes);
server.all('*', (req, res) => {
return handle(req, res)
})
server.listen(port, (err) => {
if (err) throw err
log.logger.log({
level: "info",
message: `Server was started on ${port}`,
additional: "properties",
are: "passed along",
});
console.log(`> Ready on http://localhost:${port}`)
})
})
All right, so I figured it out finally. The configuration for Openlitespeed was set, so that it could create as many httpd workers as it wants. Therefore, when a new was created and the requests went over to that one, it seems the authentification did not stick. I have fixed this by setting the "Number of Workers" to 1 under Server Configuration -> Server Process -> Number of Workers.
As for my server.js file I used to setup nextjs and openlitespeed:
const express = require("express");
const next = require("next");
const passport = require("passport");
const redis = require("redis");
const session = require("express-session");
const { v4: uuidv4 } = require("uuid");
const path = require("path");
const log = require("./logger");
let RedisStore = require("connect-redis")(session);
let redisClient = redis.createClient({ auth_pass: process.env.DB_PASSWORD });
const port = parseInt(process.env.PORT, 10) || 3000;
const dev = process.env.NODE_ENV !== "production";
const app = next({ dev });
const handle = app.getRequestHandler();
app.prepare().then(() => {
const server = express();
//Json parsing
server.use(express.json());
server.use(express.urlencoded({ extended: true }));
if (dev) {
//Express session
server.use(
session({
store: new RedisStore({ client: redisClient }),
genid: function () {
return uuidv4();
},
secret: uuidv4(),
resave: false,
saveUninitialized: false,
cookie: {
secure: false,
maxAge: 86400000,
},
})
);
} else {
//Express session
server.use(
session({
store: new RedisStore({ client: redisClient }),
genid: function () {
return uuidv4();
},
secret: uuidv4(),
proxy: true,
resave: false,
saveUninitialized: false,
cookie: {
secure: true,
maxAge: 86400000,
},
})
);
}
//Passport auth
server.use(passport.initialize());
server.use(passport.session());
//Import of the passport config
const initializePassport = require("./passport-config");
initializePassport(passport);
//Login route
server.post("/login", passport.authenticate("login"), (req, res) => {
res.send({ message: "Successful login", login: true });
});
const passportLogout = function (req, res, next) {
req.logout();
next();
};
//Logout route
server.get("/logout", passportLogout, (req, res) => {
req.session.destroy();
res.redirect("/login");
});
//Import registrerings route. Pga. brugen af route i stedet for app kan vi bruge denne middleware med en anden underside, hvis vi f.eks. ville gøre så admins også kunne lave brugere.
const registerRoute = require("./routes/register-user");
server.use("/register", registerRoute);
//User routes hvor login er required. Rendering. Skal stå under called til initializepassport, ellers kan den ikke finde ud af at den er authenticated via passport, og auth.js returnerer dig derfor til login
const usersRoutes = require("./routes/user/user-routes");
server.use(usersRoutes);
//Admin routes til rendering
const adminRoutes = require("./routes/admin/admin-routes");
server.use(adminRoutes);
const indexRoutes = require("./routes/index-routes");
server.use(indexRoutes);
server.all("*", (req, res) => {
return handle(req, res);
});
server.listen(port, (err) => {
if (err) throw err;
console.log(`> Ready on ${port}`);
});
});

req.session returns undefined in the next POST request after is defined

I'm working with a back-end made with Node.js and front-end made with Angular.
I use express-sessions for login, at first, it returns the correct req.session.usuario. But in the next POST request for checking if the user is logged in it returns undefined.
Here is the app.js of node
var express = require('express');
var path = require('path');
var logger = require('morgan');
var cors = require('cors');
var session = require('express-session');
var cookieParser = require('cookie-parser');
var indexRouter = require('./routes/index');
var authRouter = require('./routes/auth');
var usersRouter = require('./routes/users');
var instructorRouter = require('./routes/instructor');
var app = express();
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, 'public')));
app.use(cookieParser());
app.use(cors( {
credentials: true,
origin: 'http://localhost:4200'
}));
app.use(session({
secret: "Shh, es un secreto",
resave: false,
saveUninitialized: true
}))
app.use('/', indexRouter);
app.use('/auth', authRouter);
// app.use('/usuario', authMiddleware.estaLogueado ,usersRouter);
app.use('/usuario', usersRouter);
app.use('/instructor', instructorRouter);
...
module.exports = app;
This is my function for the route in the auth.js
router.post('/login', (req, res, next) => {
const username = req.body.username.toLowerCase();
Usuario.findOne({
where: {
username: username
}
}).then((usuario) =>{
if (usuario) {
bcrypt.compare(req.body.password, usuario.password, function(errp, result) {
if(result){
req.session.usuario = usuario.id; // Saves the session
console.log("La sesion " + req.session.usuario);
res.json({username: usuario.username, color: usuario.color});
} else {
next(new Error("Contraseña incorrecta"));
}
});
}else{
next(new Error("Usuario invalido"));
}
}, err => {
next(new Error("Usuario invalido: " + err));
});
});
And this is the function that I use for checking if is logged in:
router.post('/logged', (req, res) => {
console.log("intento: " + req.session.usuario) // here it shows undefined
req.session.usuario ? res.json({loggedIn: true}) : res.json({loggedIn: false});
})
In Angular these are the two functions that I use, the first one is the login (which works) and the second one is the logged that returns false all the time:
login(user, pass) {
return this.http.post(server + '/auth/login',
{username: user, password: pass},
{withCredentials: true}
)
}
logged(){
return this.http.post(server + '/auth/logged', {withCredentials: true})
}
In the actual component I do:
this.authservice.logged().subscribe( (data) => {
this.loggedIn = data['loggedIn'];
console.log(data['loggedIn']);
});
What is the problem here?
I finally got the answer! I was doing everything ok but the second request was actually not including the withCredentials json as options, it was passed as body so I added empty brackets to simulate the body and now it works like a charm!

Resources