My controls look like this
return (
<div className='contentDiv'>
<Container>
<Form onSubmit={getFormData}>
<Form.Group className="mb-3" controlId="formBasicName">
<Row><Form.Control name="id" type="number" value={3} readOnly={ true }></Form.Control></Row>
<Row>
<Col>
<Form.Label>Forname:</Form.Label> <Form.Control name="firstname" type="text" placeholder="navn"></Form.Control>
</Col>
<Col>
<Form.Label>Efternavn:</Form.Label> <Form.Control name="lastname" type="text" placeholder="Efternavn"></Form.Control>
</Col>
</Row>
</Form.Group>
<Row><Button type="submit">Create user</Button></Row>
</Form>
</Container>
</div>
)
And the function that is called on submit looks like this
const getFormData = async (event) => {
const data = new FormData(event.currentTarget);
event.preventDefault();
await fetch(`/api/newMember`, {
method: 'POST',
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(data)
})
.then(res => {
console.log(res);
})
.catch(err => {
console.log(err)
})
};
If I do this in the client (and fill the form with id=3, firsname=Lucky lastname=Luke):
for (let [key, value] of data.entries()) {
console.log(key, value);
}
I get (in the console)
id 3
firstname Lucky
lastname Luke
The server post method that does not receive the data from the client, looks like this
const express = require('express');
const knex = require('knex');
const cors = require('cors');
const bodyParser = require('body-parser');
const app = express();
const port = 3001;
app.post('/api/newMember', (req, resp) => {
const { id, firstname, lastname } = req.body;
console.log(req.body);
const newMember = {
id: id,
firstname: firstname,
lastname: lastname,
};
db('members').insert(newMember)
.then(res => {
resp.send(res)
})
.catch(err => {
console.log(err);
return;
})
})
app.listen(port, () => {
console.log('Server listening on port: ' + port);
});
In the server, I have this code: console.log(req.body);
. It jsut prints {}
Can anyone figure out what I’m doing wrong? Thanks