首页 > 后端开发 > Golang > 正文

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

WBOY
发布: 2024-02-10 10:48:09
转载
1138 人浏览过

如何使用 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 之前从数据库中获取。

以上是如何使用 Dio/Flutter(前端)和 Go(后端)向 API 发送正确的请求的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:stackoverflow.com
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!