Flutter error when sending post request from API (Dio package)

81 views Asked by At

I have a code where I use Dio package in flutter to post request from an API. I checked Postman, and it returned the correct data. The problem is:

"DioException[bad response]: The request returned an invalid status code of 405."

Error from app

Error from browser console

I used Dio package in flutter to post request from an API When I used loginURL = "http://192.168.1.6/api/login", it ran successfully. However, when I uploaded the backend to the server and replaced the URL with something like LoginURL = "backend.com/api/login", it returned an error.

authentication.dart

Future<Map<String, dynamic>> login(String email, String password) async {
Dio dio = Dio();
try {
   final response = await dio.post(loginUrl, data: {
  'email': email,
  'password': password,
});
return {
  "success": true,
  "type": response.data['type'],
  "token": response.data["token"],
  "data": response.data
};
} on DioException catch (e) {
if (e.response != null) {
  if (e.response!.statusCode == 400) {
    return {"success": false, "message": "Invalid Credentials."};
  } else if (e.response!.statusCode == 422) {
    return {"success": false, "message": "Please Fill All fields"};
  }
}
return {"success": false, "message": e.toString()};
}
}
2

There are 2 answers

0
Olawale Ajepe On

You might need to look up the meaning of 405 status code:

"The HyperText Transfer Protocol (HTTP) 405 Method Not Allowed response status code indicates that the server knows the request method, but the target resource doesn't support this method. The server must generate an Allow header field in a 405 status code response. The field must contain a list of methods that the target resource currently supports."

Also check the baseUrl if is on Https or Http

0
abdalla ashraf On

you can see more details about your Dio request and response by writing this line after Dio initialization :

dio.interceptors.add(LogInterceptor());

May it help you to solve this issue