Issue
I'm creating a Flutter app and want to add login using express-session. But I have some problem with the session values not being set/fetched correctly using the Android emulator.
Server
const app = express();
const map = new Map();
const sessionParser = session({
saveUninitialized: false,
secret: '$eCuRiTy',
resave: false
});
app.use(sessionParser);
app.use(express.static('public'));
app.post('/login', function (req: any, res: any) {
console.log("enter login");
const id = uuid.v4();
console.log(`Updating session for user ${id}`);
req.session.userId = id;
res.send({ result: 'OK', message: 'Session updated' });
});
app.delete('/logout', function (req: any, response: any) {
console.log("enter logout");
console.log("Logout user:", req.session.userId);
const ws = map.get(req.session.userId);
console.log('Destroying session');
req.session.destroy(function () {
if (ws) ws.close();
response.send({ result: 'OK', message: 'Session destroyed' });
});
});
When I call above auth functions from Postman using
- Post: http://localhost:7000/login
- Delete: http://localhost:7000/logout
I get the following output in my loggs
- enter login
- Updating session for user 1a9a9e62-e972-4a28-82d3-892d282b6321
- enter logout
- Logout user: 1a9a9e62-e972-4a28-82d3-892d282b6321
- Destroying session
But when I try to make the same calls from my flutter application with the following code I get req.session.userId
as undefined
static const url = "10.0.2.2:7000";
login() {
http.post(Uri.parse('http://$url/login'));
}
logout() {
http.delete(Uri.parse('http://$url/logout'));
}
- enter login
- Updating session for user b0e9768e-b24c-4b1a-9a7c-a3fd58ef2ede
- enter logout
- Logout user: undefined
- Destroying session
Any ideas why I am getting undefined using the emulator?
Solution
When using flutter you need to pass the cookies manually,
So i got a little helper class from this POST
Now i can just call post,get etc through the Session
class
class Session {
Map<String, String> headers = {};
Future<Map> get(String url) async {
http.Response response = await http.get(Uri.parse(url), headers: headers);
updateCookie(response);
return json.decode(response.body);
}
Future<Map> post(String url, dynamic data) async {
http.Response response =
await http.post(Uri.parse(url), body: data, headers: headers);
updateCookie(response);
return json.decode(response.body);
}
Future<Map> delete(String url) async {
http.Response response =
await http.delete(Uri.parse(url), headers: headers);
updateCookie(response);
return json.decode(response.body);
}
void updateCookie(http.Response response) {
String? rawCookie = response.headers['set-cookie'];
if (rawCookie != null) {
int index = rawCookie.indexOf(';');
headers['Cookie'] =
(index == -1) ? rawCookie : rawCookie.substring(0, index);
}
}
}
Answered By - PEPEGA
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.