Reputation: 55
Hi guys there have been an error in my site for quite long and I have searched whole internet for the answers but didn't found any solutions here is my onsubmit code
onSubmit = () => {
fetch("http://localhost:2000/signin", {
method: "post",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
email: this.state.signinEmail,
password: this.state.signinPassword,
}),
})
.then((response) => response.json())
.then(console.log(this.state.signinEmail, this.state.signinPassword))
.then((data) => console.log(data));
};
Also i have checked the response of the network tab it says success but getting this error don't know how to get rid of it. I have also checked the solution of the Stackoverflow that write Accept:application/json but still didn't worked,but it gives me "bad request" error The backend code is:
app.post("/signin", (req, res) => {
if (
req.body.email === database.users[0].email &&
req.body.password === database.users[0].password
) {
res.send("success");
} else {
res.status(400).json("error logging in");
}
});
I have also tested it through Postman it works successfully on it with no errors.
This the json server.
Upvotes: 2
Views: 13643
Reputation: 1
Thanks Ayaz, as suggested when I modified the code to
.then((response) => response.text())
.then((data) => console.log(data));
It helped me to see the response which appeared in the console as a text, it was a redirect to a login page and it was in HTML, hence it was not valid Json.
I solved my problem by adding [AllowAnnoymous]
to my post method in the controller.
Hopes this helps someone, I was bugged down for hours.
Upvotes: 0
Reputation: 2121
This happens when you make a request to the server and parse the response as JSON, but it’s not JSON.
fetch('/url').then(res => res.json())
The actual request worked fine. It got a response. But the res.json()
is what failed.
The root cause is that the server returned HTML or some other non-JSON string.
You can try changing res.json()
to res.text()
.
onSubmit = () => {
fetch("http://localhost:2000/signin", {
method: "post",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
email: this.state.signinEmail,
password: this.state.signinPassword,
}),
})
.then((response) => response.text())
.then((data) => console.log(data));
};
Upvotes: 10