Post Request for Appointment Planner sending null object

I completed the Appointment Planner project. So I decided to go further and add a backend to the application that would store Contacts and Appointments.

Original project: https://www.codecademy.com/projects/practice/appointment-planner

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. Any clue as to why this is happening is appreciated.

FrontEnd

import {ContactForm} from "../../components/contactForm/ContactForm";
import {TileList} from "../../components/tileList/TileList";

export const ContactsPage = (props) => {
  /*
  Define state variables for 
  contact info and duplicate check
  */

 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 Routing

const app = express();
const cors = require('cors');
const pool = require('./db/index');
const bodyParser = require('body-parser');

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}`));

This is the Database model

CREATE TABLE contacts(
    name character varying(50),
    phone bigint,
    email varchar
);

CREATE TABLE appointments(
    id serial,
    contact character varying(50),
    date DATE,
    time TIME(0)
);

As you see in the network tab. The client sents a null object to this route:

I believe you should change it to this:

  body: JSON.stringify(data)

That fixed it thank you so much!

1 Like