使用Dart向Flask发送POST请求会返回带有200状态码的OPTIONS。

huangapple go评论169阅读模式
英文:

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

问题

Here's the modified Dart code to resolve the issue with the "OPTIONS" request when making a POST request to your Flask backend. This code sets up the necessary headers to handle CORS (Cross-Origin Resource Sharing) requests properly.

void createUser({required String email, required String password}) async {
  final Map<String, String> headers = {
    'Content-Type': 'application/json',
    'Access-Control-Allow-Origin': '*',  // Add this line for CORS
  };

  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;
  }
}

The change is to add the 'Access-Control-Allow-Origin' header with the value '*' to allow requests from any origin. This should resolve the "OPTIONS" request issue when calling the createUser method from your Flutter frontend.

Please make sure that this change complies with your CORS policy and security requirements.

英文:

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&lt;String, String&gt; headers = {&#39;Content-Type&#39;: &#39;application/json&#39;};

    Map&lt;String, String&gt; data = {
      &quot;email&quot;: email,
      &quot;password&quot;: password,
    };

    try {
      final response = await http.post(Uri.parse(&quot;http://localhost:5000/register&quot;), 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(&#39;email&#39;, type=str, required=True, help=&quot;Email is required&quot;)
        arguments.add_argument(&#39;password&#39;, type=str, required=True, help=&quot;Password is required&quot;)

        user_data = arguments.parse_args()

        if User.find_user(user_data[&#39;email&#39;]):
            return {&quot;error&quot;: &quot;User already exists&quot;}, 409

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

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

curl -H &quot;Content-Type: application/json&quot; -X POST -d &#39;{&quot;email&quot;:&quot;test@test.com&quot;, &quot;password&quot;:&quot;12345678&quot;}&#39; 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] &quot;OPTIONS /register HTTP/1.1&quot; 200 -

答案1

得分: 0

通过添加CORS到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)
英文:

Fixed by adding CORS to flask

from flask_cors import CORS


app = Flask(__name__)
app.config.from_object(AppConfiguration)
cors = CORS(app)
app.config[&#39;CORS_HEADERS&#39;] = &#39;Content-Type&#39;
api = Api(app)

huangapple
  • 本文由 发表于 2023年8月11日 04:54:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/76879248.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定