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

如何从Express后端服务器返回用户ID,解决股票应用登录问题

问题根因及修复方案

1. 后端核心错误修复

你当前代码中users是存储所有用户信息的数组,匹配到的合法用户存在userResult变量内,但返回时错误读取了数组的id属性,自然无法拿到正确的用户ID。只需要把登录成功返回逻辑里的users.id修改为userResult.id即可。
另外优化建议:登录失败时返回401状态码更符合接口规范,方便后续前端统一拦截权限类错误。
修复后后端代码如下:

let users = [
    {
        id: 1,
        userName: 'user1',
        email: 'abc@email.com',
        password: 'abc'
    },
    {
        id: 2,
        userName: 'user2',
        email: '123@email.com',
        password: '123'
    }
]

app.post('/api/auth', (req, res) => {
    let userResult = users.find(user => user.email === req.body.email);
    if (userResult) {
        if (userResult.password === req.body.password) {
            res.status(200).send({
                message: true,
                user: userResult.id // 此处将原错误的users改为匹配到的userResult
            })
        } else {
            res.status(401).send({
                message: false
            })
        }
    } else {
        res.status(401).send({
            message: false
        })
    }
});

2. 前端逻辑优化

当前前端逻辑存在小问题:用户未填账号密码弹出提示后,依然会发起登录请求,不符合预期。建议把axios请求逻辑放到账号密码非空判断的else分支内,同时补充localStorage存储用户ID的逻辑。
修复后前端代码如下:

handleSubmit = e => {
    e.preventDefault()
    const request = {
        email: this.state.userEmail,
        password: this.state.userPassword
    }
    if (this.state.userEmail === '' || this.state.userPassword === '') {
        alert('请输入账号和密码')
    } else {
        axios.post(`http://localhost:3000/api/auth`, request)
            .then(res => {
                if (res.data.message) {
                    console.log(res.data.user)
                    // 存储用户ID到localStorage维持会话
                    localStorage.setItem('stockAppUserId', res.data.user)
                    // 跳转到受保护的仪表盘页面
                    this.props.history.push('/dashboard')
                    this.setState({isAuth: true, userEmail: '', userPassword: ''})
                } else {
                    alert('账号或密码错误')
                    this.setState({isAuth: false, userEmail: '', userPassword: ''})
                }
            console.log(res.data.message)
            })
            .catch(err => {
                console.log(err)
            })
    }
}

3. 后续受保护路由校验提示

做路由权限控制时,直接通过localStorage.getItem('stockAppUserId')判断是否存在有效值即可,用户退出登录时调用localStorage.removeItem('stockAppUserId')清空存储的ID即可销毁会话。

内容的提问来源于stack exchange,提问作者Kaelix

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.18 20:45:00