Reputation: 3
I'm trying to create a login for a homepage with react and node, with user details from a hard-coded database. The node backend recognises the json password and email, but I can't get the code to send the data back to the frontend to sign in.
I've tested the backend with postman to ensure I can fetch the data.
node server:
app.post('/signin', (req, res) => {
if(req.body.email === database.users[0].email &&
req.body.password === database.users[0].password) {
res.json('success');
}
else {
res.status(400).json('error logging in');
}
})
react
class Signin extends React.Component {
constructor(props) {
super(props);
this.state = {
signInEmail: '',
signInPassword: ''
}
}
onSubmitSignIn = () => {
fetch('http://localhost:5000/signin', {
method: 'post',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
email: this.state.signInEmail,
password: this.state.signInPassword
})
})
.then(user => {
if (user.id) {
this.props.loadUser(user)
this.props.onRouteChange('home');
}
})
}
database:
const database = {
users: [
{
id: '123',
name: 'andrew',
email: 'andrew@outlook',
password: 'p',
entries: 0,
joined: new Date()
},
{
id: '124',
name: 'sally',
email:' sally@outlook',
password: 'bananas',
entries: 0,
joined: new Date()
},
],
}
It works when I remove the .then(user =>)
call and go straight to this.props.onRouteChange('home')
, but remains on the signin page otherwise. It's driving me nuts, any help appreciated.
Upvotes: 0
Views: 1269
Reputation: 1728
Welcome to stackoverflow!
I think you're not sending the correct data back to the frontend or checking for the wrong data.
Your nodeJS application sends either
res.json('success');
or
res.status(400).json('error logging in');
So no matter what you're sending back a string. But on the frontend you're checking for an id
attribute on the response:
.then(user => {
if (user.id) {
this.props.loadUser(user)
this.props.onRouteChange('home');
}
})
Your user
is a response object you get after fetch
. If you rename the user
to response
and call response.json()
you can add another .then(json => {...}
where you can check your json object to be one of the strings you send by your nodeJS backend.
Upvotes: 1