简体   繁体   中英

NodeJS express-session not working on Android emulator

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

  1. enter login
  2. Updating session for user 1a9a9e62-e972-4a28-82d3-892d282b6321
  3. enter logout
  4. Logout user: 1a9a9e62-e972-4a28-82d3-892d282b6321
  5. 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'));
  }
  1. enter login
  2. Updating session for user b0e9768e-b24c-4b1a-9a7c-a3fd58ef2ede
  3. enter logout
  4. Logout user: undefined
  5. Destroying session

Any ideas why I am getting undefined using the emulator?

As i see in this question: How to make an http DELETE request with JSON body in Flutter? the "delete" verb does not send data with Flutter. You can see @Roi Snir's answer in the previous link, a way to send data with "delete" by using the .Request method of the http package.

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);
    }
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM