I use states to hold some form data in react, and what i want is, when i submit the form in react i send a post request using axios,and i want to use the form data in express. I tried req.body.params, req.body.data, req.body general,to access the request payload and they all returned undefined. Basically I want to access general(form data) in express. How can i do that?
note: the states are named general, and oneSuggestion, they are basic string states.
note:i searched similar questions for hours but none of them solved my question. if there was a solution, i couldn't find it, please excuse me.
edit: commented data, and put the states directly inside post.
React code:
function handleSubmit(e) {
e.preventDefault();
console.log(general, suggestionsForCases);
/*
let data = {
general: general,
oneSuggestion: oneSuggestion,
};
data = JSON.stringify(data);
console.log(data);
*/
let axiosConfig = {
headers: {
"Content-Type": "application/json;",
"Access-Control-Allow-Origin": "*",
},
};
axios
.post(
"http://localhost:8000/dict/",
{ general: general, oneSuggestion: oneSuggestion },
axiosConfig
)
.then((res) => console.log("success, dictionary sent,", res))
.catch((err) => {
console.log(err.response);
});
}
function handleInput(e) {
if (e.target.name == "general") {
setGeneral(e.target.value);
console.log(general);
}
if (e.target.name == "oneSuggestion") {
setOneSuggestion(e.target.value);
console.log(oneSuggestion);
}
}
return (
<div>
<form onSubmit={handleSubmit}>
<label>
general:
<textarea name="general" onChange={handleInput}></textarea>
</label>
<label>
suggestion:
<input name="oneSuggestion" onChange={handleInput}></input>
</label>
<button type="submit">submit</button>
</form>
</div>
);
}
export default AddDictionary;
express code:
const express = require("express");
const router = express.Router();
const Dictionary = require("../database/category/dictionary");
router.use(express.json());
router.get("/", (req, res) => {
console.log("success");
res.json({ msg: "success"});
});
router.post("/", (req, res) => {
console.log(req.body.general);
res.json({
msg: "success",
});
});
module.exports = router;
Ok, I found the problem. I deleted the axiosConfig from post, based on this source , and now this is the working code:
axios
.post(
"http://localhost:8000/dict/",
{ general: general, oneSuggestion: oneSuggestion }
)
.then((res) => console.log("success, dictionary sent,", res))
.catch((err) => {
console.log(err.response);
});
thank you guys for your help.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With