我很难理解我在这个POST请求上做错了什么。POST请求本身正在工作-在网络选项卡中确认。但是,我只能发布我定义的静态值,而不是来自表单字段的值。请看一看。这让我很恼火。谢谢!
注:
- 在TestForm.js中,它实际上似乎并不像我要求的那样记录响应。
- 我没有收到任何错误。
- 这确实会POST到我的服务器和Postgres中,我将在下面显示当我使用console.log时的情况。
- handleSubmit开头的console.log(sauces)实际上正确地显示了"sauces",这是输入到第一个表单字段中的任何内容。
- Project GitHub
React表单组件(TestForm.js):
function TestForm() {
const [sauce, setSauce] = useState('');
const [presentation, setPresentation] = useState('');
const handleSubmit = (e) => {
e.preventDefault();
fetch('http://jyh:3000', {
method: 'POST',
headers: {'Content-Type':'application/json'},
body: JSON.stringify({
"test_name": sauce,
"test_sauce": presentation,
}),
}).then((res) => {
console.log(res.json());
return res.json();
}).catch((err) => {
console.log(err.message);
});
};
return (
<form onSubmit={handleSubmit}>
<div className="color-section" id="reviewASauce">
<div className="container-fluid">
<h2>Review a Sauce</h2><br />
Trying a sauce that is already in our database? Review it!
<br />
<br />
<br />
<h2>Sauce Name</h2>
<Form.Label htmlFor="test_name">
</Form.Label>
<Form.Control
type="text"
id="test_name"
aria-describedby="test_name"
placeholder="Input the name of the sauce here."
value={sauce}
onChange={(e) => setSauce(e.target.value)}
/>
<Form.Text id="test_name" muted>
</Form.Text>
<br />
<br />
<Form.Label htmlFor="test_sauce">
</Form.Label>
<Form.Control
type="text"
id="test_sauce"
aria-describedby="test_sauce"
placeholder="Input the name of the sauce here."
value={presentation}
onChange={(e) => setPresentation(e.target.value)}
/>
<Form.Text id="test_sauce" muted>
</Form.Text>
<br />
<br />
<Button variant="dark" type="submit">
Submit
</Button>
</div>
</div>
</form>
);
}
export default TestForm;
服务器索引. js:
app.post('/', async (req, res) => {
await TestTable.create({
test_name: "test_name",
test_sauce: "test_sauce",
}).then((data) => {
console.log(data.toJSON());
}).catch((err) => {
console.log(err);
});
});
点击提交时终端显示的内容:
{
id: 100,
test_name: 'test_name',
test_sauce: 'test_sauce',
updatedAt: 2022-12-21T02:54:42.447Z,
createdAt: 2022-12-21T02:54:42.447Z
}
I have tried to change and arrange both the HandleSubmit function as well as my app.post, but no matter what I do I cannot seem to get the form data from TestForm.js to index.js.
What form looks like on front end
1条答案
按热度按时间ee7vknir1#
在您的Server index.js中,您没有使用从前端发送的参数。
看起来您正在为您的服务器使用express。
试着做一些
请检查:How to access the request body when POSTing using Node.js and Express?