I'm building a simple React app that would create contacts and use them to schedule meetings.
I'm tried to build a backend that would save contacts submitted by client to a database. I used Express for the server and routing and postgresql for the database.
However after I implemented a post request method for adding contacts, the backend receives a null empty object after submitting a new contact. I included the frontend code component that implements the post request and the backend router.
Frontend
export const ContactsPage = (props) => {
const [name, setName] = useState('');
const [phone, setPhone] = useState('');
const [email, setEmail] = useState('');
const [duplicate, setDuplicate] = useState(false);
const handleSubmit = (e) => {
e.preventDefault();
/*
Add contact info and clear data
if the contact name is not a duplicate
*/
if(!duplicate){
props.addContacts(name,phone,email);
setName('');
setPhone('');
setEmail('');
}
//Post request
const data = { name, phone, email };
fetch('http://localhost:5000/api/contacts', {
method: 'POST',
mode: 'cors',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
data: JSON.stringify(data)
}).then(() => {
console.log({name,phone,email})
}).catch(error => {
// handle network errors
console.error(error);
});
};
/*
Using hooks, check for contact name in the
contacts array variable in props
*/
useEffect(() => {
const nameIsDuplicate = () => {
const found = props.contacts.find((contact) => contact.name === name);
if (found !== undefined) {
return true;
} else {
return false;
}
};
if (nameIsDuplicate()===true) {
setDuplicate(true);
} else {
setDuplicate(false);
}
}, [name,duplicate,props.contacts]);
return (
<div>
<section>
<h2>
Add Contact
{duplicate? "- Name already exists -" : ""}
</h2>
<ContactForm
name = {name}
email = {email}
phone = {phone}
setName = {setName}
setEmail = {setEmail}
setPhone = {setPhone}
onSubmit = {handleSubmit} />
</section>
<hr />
<section>
<h2>Contacts</h2>
<TileList
list={props.contacts}
/>
</section>
</div>
);
};
Backend:
app.use(bodyParser.json());
app.use(cors({ origin: 'http://localhost:3000'}));
app.get('/api/contacts', (request,response,next) => {
pool.query('SELECT * FROM contacts', (err, res) => {
if (err) return next(err);
response.json(res.rows);
});
});
app.post('/api/contacts', (request, response, next) => {
const { name, email, phone } = request.body;
pool.query(
'INSERT INTO contacts(name, phone, email) VALUES($1, $2, $3)',
[name,phone,email],
(err, res) => {
if (err) return next(err);
response.redirect('/api/contacts');
}
);
});
app.use((err,req,res,next) => {
res.json(err);
})
const port = 5000;
app.listen(port, () => console.log(`Server started on port ${port}`));
CodePudding user response:
I figured out the problem. The post request header had the wrong key for request body. "data" instead of "body"
fetch('http://localhost:5000/api/contacts', {
method: 'POST',
mode: 'cors',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(data)