首頁 > 後端開發 > 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學習者快速成長!