My front-end form is posting data using the fetch()
function. Everything works fine and I get the correct response from the server when it runs smoothly without any interruptions. However, when I debug the server endpoint, it throws a TypeError: failed to fetch
error.
This issue is not related to CORS because the request is resolved properly once I remove the breakpoint from the API.
exports.add_new_data = async (req, res, next) => {
promise = db.addData(req.body.data); //this is where I have the breakpoint and pause
promise
.then((data) => {
res.status(201).send({
success: true,
message: "Data added successfully",
error: null,
data: data,
});
})
.catch((err) => {
res.status(500).send({
success: false,
message: err.message,
error: err,
});
});
};
And here is the code for the frontend:
render() {
return (
<div>
<form>
<label htmlFor="Name">Name: </label>
<input id="Name" type="Text" onChange={this.updateName} />
<label htmlFor="Age">Age: </label>
<input id="Age" type="Text" onChange={this.updateAge} />
<button onClick={this.submit}>submit</button>
</form>
</div>
);
}
submit = async () => {
try {
let data = [];
data.push({ name: this.state.name, age: this.state.age });
let res = await fetch(`${d}/people/add-person`, {
// Error immediately thrown here
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ data }),
});
let receivedData = await res.json();
alert(`Status ${res.status}`);
if (res.status === 200) {
alert("Added Successfully");
} else {
alert(`${receivedData}`);
}
} catch (error) {
alert(error);
}
alert(`Name: ${this.state.name} Age: ${this.state.age}`);
};