I am having difficulty understanding what I'm doing wrong on this POST request. The POST request itself is working which I confirmed in the network tab.
However, I am only able to post static values that I define, rather than the values from the form fields. Please have a look. This is driving me up the wall. Thank you!
Notes:
- In
TestForm.js
it doesn't actually seem toconsole.log
the response as I'm asking it to. - I receive no errors.
- This does POST to my server, and into Postgres, and I will show below what that looks like when I
console.log
. console.log(sauces)
at the start ofHandleSubmit
does in fact show "sauces" currectly, which is whatever is input into the first form field.- GitHub Repository
The React Form Component (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;
Server index.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);
});
});
What the terminal displays when clicking submit:
{
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
.