flutterdartflaskflask-restfuldart-http

Post request with dart to flask gives out OPTIONS with code 200


I'm trying to do a post request with dart to my flask back-end, this is my post request on dart

void createUser({required String email, required String password}) async{
    final Map<String, String> headers = {'Content-Type': 'application/json'};

    Map<String, String> data = {
      "email": email,
      "password": password,
    };

    try {
      final response = await http.post(Uri.parse("http://localhost:5000/register"), headers: headers, body: json.encode(data));
    } on Exception catch (e) {
      rethrow;

    }
  }

and this is the post flask

    def post(self):
        arguments = reqparse.RequestParser()

        arguments.add_argument('email', type=str, required=True, help="Email is required")
        arguments.add_argument('password', type=str, required=True, help="Password is required")

        user_data = arguments.parse_args()

        if User.find_user(user_data['email']):
            return {"error": "User already exists"}, 409

        user = User(**user_data)
        user.save_user()
        return {"message": "User created successfully"}, 201

Was able to do a post request with curl normally like this

curl -H "Content-Type: application/json" -X POST -d '{"email":"test@test.com", "password":"12345678"}' http://localhost:5000/register

But when I run it on my flutter front-end that calls the createUser method it shows this on flask terminal

127.0.0.1 - - [10/Aug/2023 17:45:59] "OPTIONS /register HTTP/1.1" 200 -

Solution

  • Fixed by adding CORS to flask

    from flask_cors import CORS
    
    
    app = Flask(__name__)
    app.config.from_object(AppConfiguration)
    cors = CORS(app)
    app.config['CORS_HEADERS'] = 'Content-Type'
    api = Api(app)