Reputation: 451
So basically I have a login I made that sends post data everytime a user presses the login button
sendLogin(e){
e.preventDefault();
fetch('/users', {
method: 'POST',
body: JSON.stringify({
email: this.email.value,
password: this.password.value
}),
}).then(function(response) {
return response
}).then(function(body) {
console.log(body);
});
}
render(){
return (
<form onSubmit={(event) => this.sendLogin(event)} class="asdf">
<input type="text" placeholder="email" ref={(input) => { this.email = input}}/>
<input type="password" placeholder="password" ref={(input) => { this.password = input }}/>
<input type="submit" placeholder="submit"/>
</form>
)
}
And in my express server.js code, I have it setup to console log the data we get
app.post('/users', function(req, res) {
var user = req.body;
res.end('Success');
console.log('GOT A REQUEST');
console.log(user);
})
The console.log(user) part isn't working at all, and in the client code the console.log(body); part also doesn't work at all. Any idea on how to fix this up?
EDIT: THEY BOTH COME UP AS UNDEFINED
Also when I changed return response to return response.json it gives me this error
Uncaught (in promise) SyntaxError: Unexpected token S in JSON at position 0
Promise rejected (async)
Upvotes: 0
Views: 607
Reputation: 58593
The console.log(user) part isn't working at all, and in the client code the console.log(body); part also doesn't work at all. Any idea on how to fix this up?
That's becuase of sequence of execution :
Change this :
res.end('Success');
console.log('GOT A REQUEST');
console.log(user);
To :
console.log('GOT A REQUEST');
console.log(user);
res.end('Success');
Uncaught (in promise) SyntaxError: Unexpected token S in JSON at position 0 Promise rejected (async)
Reason for this error is res.end('Success');
, you are sending String
in response instead of JSON
, try res.end({data : logged_in_user_data});
.
NOTE : If you need to respond with data, instead use methods such as res.send() and res.json().
Upvotes: 1