我在React中使用状态来保存一些表单数据,当我提交表单时,我想使用axios发送POST请求,并且想在express中使用表单数据。我试过使用req.body.params
、req.body.data
、req.body general
来访问请求体(payload),但它们都返回未定义(undefined)。基本上,我想在express中访问general
(表单数据)。我怎么做呢?
注:这些状态的名称为“general”和“oneSuggestion”,它们是基本字符串状态。
注:我已经搜索了数小时相似的问题,但没有解决我的问题。如果有解决方案,而我找不到,请原谅我。
编辑:注释掉了data,直接将states放在了post请求中。
React 代码:
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 代码:
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;
{params:{general:""}}
而不是{general:""}
。 - tklgaxios.post(“http://localhost:8000/dict/”,{general:general,oneSuggestion:oneSuggestion},axiosConfig)
。 - dumblessar