1

I have a PHP laravel backend running with Auth. How can I log in from flutter?

I tested it registering and logging in with laravel blade views, and then with a simple HTML form and it worked. I'm trying to log in from my flutter app now but always get the same exception:

"SocketException: OS Error: Connection Refused, errno = 111, address = 127.0.0.1, port = 41978"

Except for the port increments each time I try.

I did this simple call first from a file in my desktop and successfully logged in:

    <form method="POST" action="http://127.0.0.1:8000/login">
        <input id="email" name="email" type="email" />
        <input id="password" name="password" type="password" />
        <button type="submit">login</button>
    </form>

This is my flutter HTTP request code:

    http.Response webMessage;
    webMessage = await http.post('http://127.0.0.1:8000/login',
        body: {
            'email': myUser,
            'password': myPass,
        },
        headers: {
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
        'Content-Type': 'application/x-www-form-urlencoded'
        },
        encoding: Encoding.getByName('utf-8'),
    ).timeout(_timeout);

I also tried with Accept and Content-Type: 'application/json'. Sending a string, a Map.

I also set this in VerifyCsrfToken Middleware:

    protected $except = [
        'login',
    ];

I expect the request to successfully log the user in, and respond with a session and token cookie, to use in future requests.

Thanks!

Samet ÖZTOPRAK
  • 3,112
  • 3
  • 32
  • 33
Joe
  • 19
  • 1
  • 5

3 Answers3

5

If you're using an Android emulator and trying to access a local server in your computer, the IP should not be 127.0.0.1 nor localhost, given that the server is not in the phone. Try using 10.0.2.2 as explained here.

1

Another way could be to use your Android Debug Bridge (ADB).

Find the path to your used adb in your Taskmanager. Open an console and navigate to that folder. There you can execute the following command, to map your virtual divces port to your computers port:

adb reverse tcp:3001 tcp:8000
adb reverse tcp:(phones port) tcp:8000(computers port)

Then you should be ablte to use 127.0.0.1 or localhost

Felix Gerber
  • 1,615
  • 3
  • 30
  • 40
0

I was having same issue, with .Net Core Web Api project running on debug mode as backend service in VS19 executing on IIS Express and while sending http request from android emulator for Flutter project.

To resolve this, go to your Web.Api project properties and then Debug tab, then modify port of AppUrl:http://localhost:[your port] and then set your android baseUrl as http://10.0.2.2:[your port] for http request. It worked for me and hope will help others too.

NepoKale
  • 55
  • 5