You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React+Golang+MySQL登录功能故障排查求助

登录功能故障排查求助

我正在开发仪表盘的登录功能,但始终定位不到故障原因,尝试过多种配置方案都没有进展,参考平台文档也无法理解问题所在。

后端Handler Controller(Go)

func Login(username string, pass string) map[string]interface{} {
    db := GetConnection()
    user := &models.User{}
    // sql := "SELECT * FROM users WHERE username'" + user.Username + "'and password ='" + user.Password + "'"

    if db.Where("username = ?", username).First(&user).RecordNotFound() {
        return map[string]interface{}{"message": "Usuario no encontrado"}
    }

    passErr := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(pass))

    if passErr == bcrypt.ErrMismatchedHashAndPassword && passErr != nil {
        return map[string]interface{}{"mesagge": "Usuario o contraseña incorrectos"}
    }

    // buscar cuenta usuario

    accounts := []models.ResponseAccount{}

    db.Table("accounts").Select("id, name").Where("user_id = ?", user.ID).Scan(&accounts)

    // Configuración del response
    responseUser := &models.ResponseUser{
        ID:       user.ID,
        Username: user.Username,
        Accounts: accounts,
    }

    defer db.Close()

    fmt.Println(responseUser)

    //Entrada token

    tokenContent := jwt.MapClaims{
        "user_id": user.ID,
        "expiry":  time.Now().Add(time.Minute ^ 60).Unix(),
    }

    jwtToken := jwt.NewWithClaims(jwt.GetSigningMethod("HS256"), tokenContent)
    token, err := jwtToken.SignedString([]byte("TokenPassword"))
    HandleErr(err)

    var response = map[string]interface{}{"Message": "Bienvenido"}
    response["jwt"] = token
    response["data"] = responseUser

    return response
}

前端Axios配置

import axios from "axios";

export class AdminService {
    baseUrl = "http://localhost:3001/persona/api/";
    async login() {
        const res = await axios.post(this.baseUrl + "login");
        return res.data;
    }
}
export default new AdminService();

前端Login组件配置

class Login extends React.Component {
    state = {
        form: {
            "username": "",
            "password": ""
        },
        error: false,
        errormsg: ""
    }

    manageChange = async (e) => {
        this.setState({
            form: {
                ...this.state.form,
                [e.target.name]: e.target.value,
            }
        })
        console.log(this.state.form)
    }

    handleClick = (e) => {
        e.preventDefault();
        AdminService.login(this.state.form).then((response) => {
            console.log(response)
            if (response.data.status === 200) {
                this.props.history.push('/dashboard');
            }
            else {
                this.setState({
                    error: true,
                    errormsg: response.data.message
                })
            }
        })
    }

    render() {
        return (
            <React.Fragment>
                <section >
                    <div class="container" >
                        <div class="top"></div>
                        <div class="bottom"></div>
                        <div class="center">
                            <img src={LogoIndex} id='logo-df' />
                            <form >
                                <input placeholder="Usuario" name="username" type="text" onChange={this.manageChange} />
                                <input placeholder="Contraseña" name="password" type="password" onChange={this.manageChange} />
                                <button onClick={this.handleClick} type='submit' className='corner-button' >Entrar</button>
                            </form>
                        </div>
                    </div>
                </section>
            </React.Fragment>
        )
    }
}

错误截图

登录功能错误截图

关键问题点梳理

  • Axios未传递登录参数:AdminService.login方法未接收参数,axios.post也没有携带用户名和密码,导致后端无法获取登录凭证。
  • 密码校验逻辑问题:判断密码错误的条件里passErr != nil是冗余判断;返回的错误字段拼写错误:mesagge应为message。
  • JWT过期时间计算错误:time.Minute ^ 60是位运算,无法得到60分钟的过期时间,应改为60 * time.Minute或time.Hour。
  • 前端响应判断逻辑错误:后端返回的结构中不存在response.data.status,前端判断条件不成立,无法正常跳转或提示错误。
  • setState异步问题:manageChange中直接打印this.state.form会输出旧值,因为setState是异步操作,需通过回调函数查看更新后的值。

内容的提问来源于stack exchange,提问作者Edwin Fernando Pirajan Arevalo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 21:22:01