0

When I use try and catch to use the API insert operation and the operation inserted successfully, but unfortunately the toast message doesn't print "signed up successfully", it prints this:

"Error:  ClientException: XMLHttpRequest error., uri="http://localhost/dashboard/help_me/signup.php"
  Future<void> SignupClient() async {
    if (name.text!= "" || phone.text!= "") {
      try {

        var res = await http.post(
          Uri.parse(ApisConnect.signupApi),
          body: 
          {
            "name": name.text,
            "phone": phone.text,
          }
        );

        var response = jsonDecode(res.body);

        if (response["success"] == true) {
          Fluttertoast.showToast(msg: 'signed up successfully');
        } else if (response["success"] == false) {
          Fluttertoast.showToast(msg: 'try again');
        }


      } catch (e) {
        Fluttertoast.showToast(msg: 'Error $e');
      }
    }
  }

I tried to remove try and catch or change this.

1
  • Sounds like a CORS error. Commented Jul 7, 2024 at 2:03

1 Answer 1

0

The issue you're encountering is likely due to a CORS (Cross-Origin Resource Sharing) error. Try this:

1-print the response body and headers to the terminal. This will help you understand what the server is returning and whether the necessary CORS headers are present.

2-Ensure your server's response includes the necessary CORS headers. The server should allow requests from your application's origin by including headers. You have to enable CORS in API Gateway, like this:

<?php
// Allow from any origin
header("Access-Control-Allow-Origin: *"); //add this line for your flutter app would probably work.

// Allow specific HTTP methods
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");

// Allow specific headers
header("Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With");

// Handle preflight requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    // Indicate allowed methods and headers
    header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
    header("Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With");
    exit(0);
...

3- Also check out this questions too: IN Flutter Web getting 'XMLHttpRequest' error while making HTTP call and this one API Gateway CORS: no 'Access-Control-Allow-Origin' header

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.