Home >Backend Development >Golang >How to send correct requests to API using Dio/Flutter (frontend) and Go (backend)
php Xiaobian Yuzai brings you a guide on using Dio/Flutter (front-end) and Go (back-end) to send correct requests to the API. During the development process, interacting with APIs is an unavoidable task. However, ensuring the accuracy and validity of requests is not easy. This article will introduce you in detail how to use Dio/Flutter and Go to send correct requests, making your development work smoother and more efficient. Whether you are a beginner or an experienced developer, this article will provide you with valuable guidance and tips. Let’s explore together!
I'm testing this in Android Studio right now. Here's the Go code I'm trying to use in a Flutter frontend:
func Login(c *gin.Context) { // Get email and password off of req body var body struct { Email string Password string } if c.Bind(&body) != nil { c.JSON(http.StatusBadRequest, gin.H{ "error": "Failed to read body", }) return } var user models.User if user.ID == 0 { c.JSON(http.StatusBadRequest, gin.H{ "error": "Invalid email and/or password", }) return } // Lookup user by email, including records where deleted_at is NULL if err := initializers.DB.Where("email = ? AND deleted_at IS NULL", body.Email).First(&user).Error; err != nil { c.JSON(http.StatusBadRequest, gin.H{ "error": "Invalid email and/or password", }) return } // Compare passwords err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(body.Password)) if err != nil { c.JSON(http.StatusBadRequest, gin.H{ "error": "Invalid email and/or password", }) return } // Generate JWT Token token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{ "sub": user.ID, "exp": time.Now().Add(time.Hour * 24 * 30).Unix(), }) tokenString, err := token.SignedString([]byte(os.Getenv("SECRET"))) if err != nil { c.JSON(http.StatusBadRequest, gin.H{ "error": "Failed to create token", }) return } // Send back c.SetSameSite(http.SameSiteLaxMode) c.SetCookie("AuthZ", tokenString, 3600*24*30, "", "", false, true) c.JSON(http.StatusOK, gin.H{}) } //main,go r.POST("/login", controllers.Login)
I keep getting 400 error codes and I'm trying to analyze why. Here's how I send the request:
void postLogin(String email, String password) async { Response response; response = await _dio.post('$baseUrl/login', data: { 'email': email, 'password': password, }); } ... try { postLogin( emailController.text, passwordController.text); print('Login successful'); } catch (error) { print('Login failed: $error'); // Print Dio error message if (error is DioError) { print('Dio error message: ${error.message}'); } setState(() { errorText = 'Login failed. Please check your credentials.'; }); } finally { setState(() { isLoading = false; }); }
The API works in Postman and through other testing methods, but not in Android Studio, at least not the way I use Dio.
thanks for your help.
This looks like your problem:
var user models.User if user.ID == 0 { c.JSON(http.StatusBadRequest, gin.H{ "error": "Invalid email and/or password", }) return }
Assuming that the ID
on models.User
is just an int
, the default is always zero! You might want to load the user, e.g. get it from the database before checking the ID
.
The above is the detailed content of How to send correct requests to API using Dio/Flutter (frontend) and Go (backend). For more information, please follow other related articles on the PHP Chinese website!