我现在正在 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
}
假设
ID
上的 models.User
只是一个 int
,则默认 始终为零!您可能想要加载用户,例如在检查 ID
之前,从数据库中获取。