How to send correct requests to API using Dio/Flutter (frontend) and Go (backend)

WBOY
Release: 2024-02-10 10:48:09
forward
1142 people have browsed it

如何使用 Dio/Flutter(前端)和 Go(后端)向 API 发送正确的请求

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!

Question content

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)
Copy after 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;
                          });
                        }
Copy after login

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.

Solution

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
}
Copy after login

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!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!