Reputation: 181
I'm trying to build a Login / Register form with react and node / express / (mongo) as my backend. The backend works fine. When I send a POST request (with postman) to /register, everything works fine and the credentials are stored in the DB.
I tried to implement the form now with react on the client-side, but when I try to POST I always get the error: Unhandled Rejection (TypeError): Failed to fetch
.
This is my code:
import React, { Component } from 'react';
class Register extends Component {
state = { email: '', password: '' };
handleInputChange = event => {
const { value, name } = event.target;
this.setState({
[name]: value
});
};
onSubmit = event => {
event.preventDefault();
fetch('localhost:3000/register', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
email: this.state.email,
password: this.state.password
})
});
};
render() {
return (
<form onSubmit={this.onSubmit} noValidate>
<h1>Login</h1>
<input
type="email"
name="email"
placeholder="Enter email"
value={this.state.email}
onChange={this.handleInputChange}
/>
<input
type="password"
name="password"
placeholder="Enter password"
value={this.state.password}
onChange={this.handleInputChange}
/>
<input type="submit" value="Submit" />
</form>
);
}
}
export default Register;
Help would be appreciated:)
Upvotes: 0
Views: 4936
Reputation: 477
In my case, inserting "http://" before "localhost" worked!
onSubmit = event => {
event.preventDefault();
fetch('http://localhost:3000/register', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
email: this.state.email,
password: this.state.password
})
});
};
Upvotes: 0
Reputation: 17858
You need to use then block to actually call your api.
onSubmit = event => {
event.preventDefault();
fetch("localhost:3000/register", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
email: this.state.email,
password: this.state.password
})
})
.then(res => {
console.log("response: ", res);
})
.catch(err => {
console.log("error:", err);
});
};
Upvotes: 3