skip to Main Content

I’m making an app that has a login function. It calls an HTTP POST request to API on my localhost to check the validity of the username and password and if it matches the data on PhpMyAdmin then it will route to the member page.

However, I want to change the await http.post from localhost XAMPP link to a public API link on my hosting. But it throws some errors whenever I do it and when I click on login button nothing happened. Here’s the code:

class _MyHomePageState extends State<MyHomePage> {
  TextEditingController user = new TextEditingController();
  TextEditingController pass = new TextEditingController();

  String msg = '';

  Future<List> _login() async {
    final response =
        await http.post("http://tunnamacbook.local/login.php", body: {
      "username": user.text,
      "password": pass.text,
    });

    var datauser = json.decode(response.body);

    if (datauser.length == 0) {
      setState(() {
        msg = "Đăng nhập thất bại";
      });
    } else {
      if (datauser[0]['level'] == 'admin') {
        Navigator.pushReplacementNamed(context, '/AdminPage');
      } else if (datauser[0]['level'] == 'member') {
        Navigator.pushReplacementNamed(context, '/MemberPage');
      }

      setState(() {
        username2 = datauser[0]['name'];
      });
    }

    return datauser;
  }

...there's more but it's unnecessary to show here...

Here’s the errors:

[VERBOSE-2:ui_dart_state.cc(209)] Unhandled Exception: FormatException: Unexpected end of input (at character 1)
^
#0      _ChunkedJsonParser.fail (dart:convert-patch/convert_patch.dart:1405:5)
#1      _ChunkedJsonParser.close (dart:convert-patch/convert_patch.dart:523:7)
#2      _parseJson (dart:convert-patch/convert_patch.dart:41:10)
#3      JsonDecoder.convert (dart:convert/json.dart:506:36)

The errors are the blue lines below:
VSCode errors in blue

2

Answers


  1. Chosen as BEST ANSWER

    I figured it out. It was the problem with the CORS Policy. Setting a CORS allow header in every http API call fixed it. For those who want an example code for this problem, search on Google for CORS allow header for Flutter http call. Since I switched my mobile app programming framework to React Native for better support and a larger Stackoverflow community so I can't write code for this problem in Flutter anymore.


  2. You need to just add ‘Access-Control-Allow-Origin’: ‘*’ in header

    import 'dart:convert';
    
    Future<void> postData() async {
      final url = Uri.parse('https://example.com/api/login');
      final headers = {`enter code here`
        'Content-Type': 'application/json',
        'Access-Control-Allow-Origin': '*',
      };
      final body = json.encode({
        'email': '[email protected]',
        'password': 'password123',
      });
    
      final response = await http.post(url, headers: headers, body: body);
      final responseData = json.decode(response.body);
    
      // Process response data
    }
    
    It's possible that the API server you're accessing does not allow cross-origin requests. In that case, you may need to contact the API provider and ask them to add the necessary CORS headers to their server configuration. 
    
    To allow cross-origin requests from a localhost API, you can add the appropriate CORS headers to the server's response. In the case of a Node.js/Express server, you can use the cors middleware to do this.
    
    Here's an example of how to use the cors middleware in an Express app:
    
    If you want to restrict cross-origin requests to specific domains, you can pass an options object to the cors function with a origin property set to an array of allowed origins. For example:
    
    const express = require('express');
    const cors = require('cors');
    const app = express();
    
    const corsOptions = {
      origin: ['http://localhost:3000', 'http://localhost:4000']
    };
    
    app.use(cors(corsOptions));
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search