如何从express后端服务器返回用户id



处理股票应用程序的登录。当用户输入他们的电子邮件和密码时,当前硬编码在我的服务器中的用户ID将返回到控制台。我将使用该ID将其保存到本地存储,以保持会话有效,并允许访问我的受保护路由。我无法使用当前逻辑返回用户ID。

后端

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: users.id
})
} else {
res.status(200).send({
message: false
})
}
} else {
res.status(200).send({
message: false
})
}
});

前端

handleSubmit = e => {
e.preventDefault()
const request = {
email: this.state.userEmail,
password: this.state.userPassword
}
if (this.state.userEmail === '' || this.state.userPassword === '') {
alert('Enter Username and Password')
} else {
this.setState({userEmail: '', userPassword: ''})
}
axios.post(`http://localhost:3000/api/auth`, request)
.then(res => {
if (res.data.message) {
console.log(res.data.user)
//add user ID to local storage.
//this.props.history.push('/dashboard') Re-directs to dashboard page!!!
this.setState({isAuth: true})
} else {
alert('Invalid username or password')
this.setState({isAuth: false, userEmail: '', userPassword: ''})
}
console.log(res.data.message)
})
.catch(err => {
console.log(err)
})
}

如果读了几遍,发现返回的是users.id而不是userResult.id

if (userResult.password === req.body.password) {
res.status(200).send({
message: true,
user: userResult.id
})
}

最新更新