卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章35131本站已运行394

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

如何使用 dio/flutter(前端)和 go(后端)向 api 发送正确的请求

php小编鱼仔为您带来了一篇关于使用Dio/Flutter(前端)和Go(后端)向API发送正确请求的指南。在开发过程中,与API进行交互是不可避免的任务。然而,确保请求的准确性和有效性并不容易。本文将为您详细介绍如何使用Dio/Flutter和Go来发送正确的请求,让您的开发工作更加顺利和高效。无论您是初学者还是有经验的开发者,本文都将为您提供有价值的指导和技巧。让我们一起来探索吧!

问题内容

我现在正在 Android Studio 中对此进行测试。这是我尝试在 Flutter 前端中使用的 Go 代码:

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)

我不断收到 400 错误代码,我正在尝试分析原因。以下是我发送请求的方式:

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

该 API 在 Postman 中并通过其他测试方法可以工作,但在 Android Studio 中不起作用,至少在我使用 Dio 的方式中不起作用。

感谢您的帮助。

解决方法

这看起来像你的问题:

var user models.User
if user.ID == 0 {
    c.JSON(http.StatusBadRequest, gin.H{
        "error": "Invalid email and/or password",
    })
    return
}

假设 models.User 上的 ID 只是一个 int,默认始终为零!您可能想要加载用户,例如在检查 ID 之前从数据库中获取。

卓越飞翔博客
上一篇: 如何在单元测试中使用 cadence RegisterDelayedCallback 执行相同的工作流程?
下一篇: 返回列表
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏