How to manage session with httpClient Request ?

848 views
Skip to first unread message

rahul...@celeritio.com

unread,
Feb 25, 2019, 8:21:43 AM2/25/19
to Angular and AngularJS discussion

I'm trying to persist session at the server side. But Node server is not able to track client session.


What is wrong in this code?
Why I'm Not getting a session object?


Node Js (Server) - app.js


const express = require('express')
var bodyParser = require('body-parser');
var session = require('express-session');
var cors = require('cors');
const app = express()
const port = 3000

app.use(cors())
app.use(session({ secret: '2C44-4D44-WppQ38S', resave: true, saveUninitialized: true }));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.get('/', (req, res) => res.sendFile(__dirname + '/index.html'))

app.post('/dashboard', function(req, res) {
  if (req.session.username) {
    res.send({ "msg": "Dashboard Page" });
  } else {
    res.send({ "msg": "Please Login First" });
  }
});

app.route('/login').post(function(req, res) {
  if (req.session.username) {
    req.session.username = "someone";
    res.header("Content-Type", 'application/json');
    res.send({ "msg": "already logged in!" });
  } else {
    req.session.username = "someone";
    res.send({ "msg": "successfully logged In!" });
  }
});

app.route('/logout').post(function(req, res) {
  if (req.session.username) {
    req.session.destroy();
    res.send({ "msg": "successfully logged out!" });
  } else {
    req.session.destroy();
    res.send({ "msg": "session not found!" });
  }
});

app.listen(port, () => console.log(`Example app listening on port ${port}!`));


Angular (Client) - app.module.ts


import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    HttpClientModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }


Angular (Client) - app.component.ts


import { Component,OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit{
  constructor(public http: HttpClient) {}
  public loginStatus = "-"
  public dashboardStatus = "-"
  public logoutStatus = "-"
  ngOnInit(){
    this.http.post("http://192.168.1.93:3000/login",{username:"someone",password:"1234"})
    .subscribe(res => { this.loginStatus = res["msg"] });
    this.http.post("http://192.168.1.93:3000/dashboard",{data:"nothing"})
    .subscribe( res => { this.dashboardStatus = res["msg"] } );
    this.http.post("http://192.168.1.93:3000/logout",{data:"nothing"})
    .subscribe( res => { this.logoutStatus = res["msg"] });
  }
}


Angular 6 (Client) - app.html.ts


<div>
  <h1> loginStatus :  {{ loginStatus }} </h1>
  <h1> dashboardStatus :  {{ dashboardStatus }} </h1>
  <h1> logoutStatus :  {{ logoutStatus }} </h1>
</div>


Output -


loginStatus : successfully logged In!
dashboardStatus : Please Login First
logoutStatus : session not found!


Expected Output -


loginStatus : successfully logged In!
dashboardStatus : Dashboard Page
logoutStatus : successfully logged out!



Sander Elias

unread,
Feb 25, 2019, 8:41:29 AM2/25/19
to Angular and AngularJS discussion

Hi Rahul,

this.http.post("http://192.168.1.93:3000/login",{username:"someone",password:"1234"}) .subscribe(res => { this.loginStatus = res["msg"] }); 
this.http.post("http://192.168.1.93:3000/dashboard",{data:"nothing"}) .subscribe( res => { this.dashboardStatus = res["msg"] } ); 
this.http.post("http://192.168.1.93:3000/logout",{data:"nothing"}) .subscribe( res => { this.logoutStatus = res["msg"] });

Those will fire off at the same time and will communicate in parallel with your server. So the output is correct. Make sure you do this in order instead. That will give you the result you want.

Regards
Sander

rahul...@celeritio.com

unread,
Feb 27, 2019, 12:26:31 AM2/27/19
to Angular and AngularJS discussion
Hi Sander,

Thank for your contribution, But the problem is not solved I've tried with the sequence and also tried to make rest call with the same httpClient object but still, It's not working.

I've used the JQuery library to make server calls but angular is preventing me to keep track of client session. Without angular, I've tried the same JQuery Statement with (HTML + Javascript) and It's working.

How should I configure angular to handle session at the server side?

Sequence Example : 

this.http.post("http://192.168.1.93:3000/login",{username:"someone",password:"1234"}).subscribe(res => {
this.loginStatus = res["msg"];
this.http.post("http://192.168.1.93:3000/dashboard",{data:"nothing"}).subscribe( res => {
this.dashboardStatus = res["msg"]
this.http.post("http://192.168.1.93:3000/logout",{data:"nothing"}).subscribe( res => {
this.logoutStatus = res["msg"]
});
});
});


Regards
Rahul J

Sander Elias

unread,
Feb 27, 2019, 1:26:16 AM2/27/19
to Angular and AngularJS discussion
Hi Rahul,

Try this:
loginStatus: any;
dashboardStatus: any;
logoutStatus: any;

loginAndOut$ = this.http
username: 'someone',
password: '1234'
})
.pipe(
tap(result => console.log(result)), // log the response to console
tap(res => (this.loginStatus = res['msg'])),
flatMap(() =>
data: 'nothing'
})
),
tap(result => console.log(result)), // log the response to console
tap(res => (this.dashboardStatus = res['msg'])),
flatMap(() =>
this.http.post('http://192.168.1.93:3000/logout', { data: 'nothing' })
),
tap(result => console.log(result)), // log the response to console
tap(res => (this.logoutStatus = res['msg']))
);

subscription = this.loginAndOut$.subscribe(() => console.log('done'));

when you have done that, can you share the results from your browser dev console?

Regards
Sander



rahul...@celeritio.com

unread,
Feb 27, 2019, 1:54:00 AM2/27/19
to Angular and AngularJS discussion
Hi Sander,

I've tried your solution. Sorry to inform you that It is also not working.

Should I share you git or bitbucket repository to take a look at this.
And Thanks! I really appreciate the time and effort you put into these.

Console Result -

Screenshot from 2019-02-27 12-18-11.png

Sander Elias

unread,
Feb 27, 2019, 3:20:12 AM2/27/19
to Angular and AngularJS discussion
Hi Rahul,

This means that your "session" isn't being kept by the browser. You said it worked when you tried with jQuery?
Please send me a link to a github repo (by private mail if you prefer) so i can check out what's going on.

Regards
Sander

Sander Elias

unread,
Feb 27, 2019, 5:41:09 AM2/27/19
to Angular and AngularJS discussion
Hi Rahul,

I updated your code to work.
The biggest part of the problem was an invalid CORS config in your server part.
Also Angular follows all the best practices on security, so it demands you set the 'with-credentials' flag.
I added an interceptor for that.


Regards
Sander

Reply all
Reply to author
Forward
0 new messages