I've been trying to create a login page but I'm getting this error called "TypeError: Failed to fetch". I have no idea where I did wrong, I checked a few StackOverflow answers, like I tried adding the event.preventdefault as I saw in one of StackOverflow answer but that didn't help.
Could someone point out the part where I'm doing wrong?
Also note: it's working fine in postman with the API. I tried the same email and password there and it's working fine in postman but getting the error with the react website.
import React, { Component } from "react";
class Login extends Component {
constructor(props) {
super(props);
this.state = {
email: "",
password: ""
};
this.onchange = this.onchange.bind(this);
}
onchange(e) {
this.setState({ [e.target.name]: e.target.value });
console.log(this.state);
}
performLogin = async event => {
event.preventDefault();
console.log("button clicked");
var body = {
password: "this.state.password",
email: "this.state.email"
};
const options = {
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json"
},
body: JSON.stringify(body)
};
const url = "/api/authenticate";
try {
const response = await fetch(url, options);
const result = await response.json();
console.log(result);
console.log(`login successful`);
window.alert("login succesful");
} catch (error) {
console.error(error);
}
};
render() {
return (
<div>
<input type="text" placeholder="emailid" onChange={this.onchange} />
<br />
<input
type="password"
placeholder="Enter your Password"
onChange={this.onchange}
/>
<br />
<button type="submit" onClick={event => this.performLogin(event)}>
Submit
</button>
</div>
);
}
}
export default Login;
one anamoly is that in postman, it accepts only when I post like I've shown below
{
"password":"pass",
"email":"admin"
}
If I remove the quotes then it gives me bad string error in postman but in codesandbox, the quotes are automatically removed when I save the sandbox. could it be because of that or is it nothing to worry about?