6

I'm using package:dio in a Flutter web application.

Whenever I send a POST request, however, it gets changed into an OPTIONS request. The function that makes the API request looks like this:

Future<LoginResponse> login(LoginRequest request) async {
    final dio = Dio(BaseOptions(baseUrl: "http://localhost:8000"));
    final response = await dio.post("/login", data: request.toJson());
    return LoginResponse.fromJson(jsonDecode(response.data));
}

This code sends an OPTIONS request to http://localhost:8000/login. If I add that endpoint to my server, it works.

If I send the POST request from postman manually it also works.

If I change this code to other methods (e.g. dio.delete(...)) it also maps to an OPTIONS request.

Why is dio rewriting my requests?

cameron1024
  • 9,083
  • 2
  • 16
  • 36
  • 4
    It's not the Dart code that's doing that, it's the browser. It's doing a CORS preflight. See https://developer.mozilla.org/en-US/docs/Glossary/Preflight_request The browser does this before sending the real request to check that the server is going to respond with the correct CORS header. – Richard Heap Jan 10 '22 at 17:45
  • Thanks, that solved my problem :) – cameron1024 Jan 11 '22 at 17:01
  • 1
    @cameron1024 how did you fixe it? – Nasreddine Bouchemel Jun 27 '22 at 16:57
  • 2
    I modified the server to accept an OPTIONS request to the same endpoint. The link Richard posted in the first comment shows what request the browser makes first. If your server doesn't respond to that OPTIONS request, the next GET/POST/etc request will fail – cameron1024 Jun 28 '22 at 08:40

0 Answers0