I’m a beginner in dealing with connecting back-end, front-end and mongodb all together so im sorry if my question isnt asked in the right place.
I was trying to let the user input some data in a text box and save the data in a value property but for some reaon its not being saved inside the databody => message variable which i really dont know why. What im trying to do is call the function that sends the data in a button tag and by the time its called the data the user inputed would be sent to the server.
The values of databody and value are [object object] and undefined respectively
Here is my ping.js file. Hope the code would make more sense!
constructor(props) {
super(props);
this.state = { brand: "Ford" };
}
handleSubmit = () => {
console.log("its running");
let databody = {
message: this.state.val,
};
console.log(" the message is :" + databody);
console.log(" the message is :" + this.val);
return fetch("http://localhost:5000/stored", {
method: "POST",
body: JSON.stringify(databody),
headers: {
"Content-Type": "application/json",
},
})
.then((res) => res.json())
.then((data) => console.log(data));
};
render() {
return (
<div className="ok2">
<textarea
className="message"
type="text"
placeholder="Write me somthing!. Also, double click to ping:) "
value={this.state.val}
></textarea>
<body>
<button
className="button"
onClick={() => {
this.magic();
this.handleSubmit(); //animation + //pinging the phone
// this.handleButtonClick(); //setVal(() => ""); //sets the value of the box to empty
}}
>
</button>
This is my index.js file in the back-end Node js
app.post("/stored", (req, res) => {
console.log("its running 2: " + req.body);
db.collection("quotes").insertOne(req.body, (err, data) => {
if (err) return console.log(err);
res.send("saved to db: " + data);
});
});
These are the errors im getting because of this problem:
im using react.js, node.js and mongodb in vs code
2
Answers
I saw your screenshot and i found cors error in screenshot.
First, you fix the cors error.
You can guide to fix cors error.
https://www.section.io/engineering-education/how-to-use-cors-in-nodejs-with-express/
https://bigcodenerd.org/enable-cors-node-js-without-express/
and then second.
Currently, I can’t understand this code.
Why it need body tag and it works in parent body?
For html syntax, please guide this.
https://www.w3docs.com/snippets/html/html5-page-structure.html
I wish my answer help you. If you have any help, you can "add a commit"
You are getting this error because of cors (Cross-Origin Resource Sharing) which just makes sure no one can make requests to an api unless he is permitted. In your backend which I believe is express you need to install cors with
npm i cors
and add these two lines of code in the file where your creating the server i.e index.js, app.js