Mohit
Mohit

Reputation: 131

Cant connect to node.js server through flutter app when requesting access to server from an android device on the same network?

I am trying to connect to a node.js server running on my laptop, i wrote a flutter application which connects to the server just fine when running through an emulator on the same laptop, but when i build an apk and install the app on my android device, its not connecting to the server. The laptop is connected to the mobile's hotspot. Also when i send the same request through the app 'REST Api Client', it connects to the server and gets the response just fine. What am i missing here or what can i try to make this work?

Future<String> _makeGetRequest(name, pass) async {
    Response response1 =
        await post(_localhost(), headers: {"username": name, "password": pass});

    print(response1.body);

    return response1.body;
  }

  String _localhost() {
    if (Platform.isAndroid)
      return 'http://192.168.43.236:3000/';
    else
      return 'http://localhost:3000';
  }

Node.js server code

import express = require('express');
import bodyParser = require('body-parser');
const app = express();

const hostname: string = '192.168.43.236';
const port = 3000;
const username = 'username';
const pass = '123456';

app.use(bodyParser.urlencoded({ extended: false }));
app.post('/', (req, res) => {
    const postBody = req.headers;
    console.log(postBody.username);
    console.log(postBody.password);

    if (req.headers.username == username && req.headers.password == pass)
    res.status(200).send('Success');
    else if (req.headers.username != username) {
        res.status(404).send('User not found');
    }
    else if (req.headers.username == username && req.headers.password != pass)
        res.status(401).send('Incorrect password');
    else
        res.status(500).send('Internal Server Error');
});

app.listen(port,hostname, () => {
    console.info(`Server running at http://${hostname}:${port}/`);

});

Upvotes: 1

Views: 1426

Answers (1)

Mohit
Mohit

Reputation: 131

Ok, so for anybody having the same issue, i got it working by providing internet permissions to my app. To do so just edit the AndroidManifest.xml file like so.

Upvotes: 2

Related Questions