DEV Community

Sebastian Gbudje
Sebastian Gbudje

Posted on

How to connect your Node/express Backend with your react Front-End(POST)

It's been a while since my last post. I was involved in a co-op/internship program and was working on an app with a team of four. Since then, I've been busy with my regular job so I haven't had the time to write. I'll be sharing a lot more in my upcoming posts on my experience.

Pre-requsite for this tutorial

  1. You have some understanding of react and react hooks
  2. You know how to set-up a basic express server
  3. You Know about the fetch API
  4. You Know about JSON

Let's Talk React

React is a JavaScript library for building user interfaces. It makes creating UI a breeze. There are of course other great Front-End frameworks like angular, Vue Svelte, etc. But for this post, we will be focusing on react.

Creating Our React Front-End.

We first need to set up our react front-end. We are going to be using the create-react app.
Run the command below in your terminal. It'll take some time to finish creating the necessary files.

npx create-react-app app-name
Enter fullscreen mode Exit fullscreen mode

The command will create a directory with whatever name chose for your app and add in the necessary files needed for your application.
Open the directory in your favorite IDE and it should have its folder structure like this
app-structure
We are going to open our src folder and change the contents of the App.js file to this

import  React from 'react'

function App() {
  return (
    <div>
      <form>
        <input placeholder="email" />
        <input placeholder="password" />
      </form>
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

*Note - I could be wrong but I believe you can now make components without having to Import React from 'react' let me know in the comments if I'm wrong.

We now have a basic form that we can use to send data to our backend. Don't worry, we'll be making that soon.

Styling our Front End

Let's add some CSS styling to our form so it doesn't look plain. In the src directory, navigate to the App.css file and paste the code below inside.

body{
  background-color: rgb(63, 63, 63);
}
.App {
  text-align: center;
  width: 50%;
  margin-left: 25%;
}

.Heading{
  text-align: center;
  color: white;
}


.btn{
  padding: 9px 25px 9px 25px;
  background-color: blueviolet;
  border: none;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;
  color: white;
  margin-left: 45px;
  border: 1px solid transparent;
  border-radius: 25px;
}

 input{
  width: 100%;
  padding: 12px 20px;
  margin: 8px 0;
  font-size: 16px;
  box-sizing: border-box;
  text-align: center;
  border: none;
  border-bottom: 2px solid blueviolet;
  outline: none;
}
Enter fullscreen mode Exit fullscreen mode

Your form should look like this
Alt Text

Using Hooks to setup our Form

Hooks are the new feature introduced in the React 16.8 version. It allows you to use state and other React features without writing a class. Hooks are the functions which "hook into" React state and lifecycle features from function components. It does not work inside classes. The source for this definition was gotten from javatpoint. That link has all you need to know about hooks if you don't know anything about them. Now we are going to update our code in the App.js file to introduce hooks. The first hook we'll be using is the useState hook.

import React, { useState } from "react";
import "./App.css";

function App() {
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");

  const handleEmail = (e) => {
    setEmail(e.target.value);
  };

  const handlePassword = (e) => {
    setPassword(e.target.value);
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    alert("User Added")
    const userData = {
      email: email,
      password: password,
    };

   try{
    const add = await fetch("http://localhost:5000/", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(userData),
    });
  console.log(add)
   }catch(err){
     console.error()
   }
  };

  return (
    <div className="Heading">
      <h1>Learning Client and Server Connection</h1>
      <div className="App">
        <form onSubmit={handleSubmit}>
          <input
            placeholder="Enter Email"
            type="email"
            onChange={handleEmail}
          />
          <input
            placeholder=" Enter Password"
            type="password"
            onChange={handlePassword}
          />
          <button type="submit" className="btn">
            Submit
          </button>
        </form>
      </div>
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

Code Explanation

I know it seems like there's a lot to follow but don't worry I'll explain. We use the useState hook to take care of the states of our email and password fields. When using the useState hook, you need to first set the initial state of whatever item you want to work with. For example, if I wanted to change the age of a cat, I would first need to specify the cat's current age then I can now set the new age of the cat to be cat = whatever age I want to change it to. In order to keep track of what's being typed into the email and password fields in react, the onChange event is added to the inputs and then given the value of a function that will set the typed in value to be the new (initial) value. What I mean is, say the cat's age is 1 but I wanted to make it 2 I would keep track of my entry (which in this case is 2) with the onChange keyword then assign that to a function that would then set 2 to be the new age of the cat.

Note- If you look at the code, you see this

 const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
Enter fullscreen mode Exit fullscreen mode

in this case, we set the password and email to be empty strings that way the handlePassword and handleEmailFunction can now update them to whatever is typed.

The handleSubmit function is what sends our data to the backend server we will be setting up next. We first start by preventing the default behavior of the form (Which is reloading the page on submit) then we create an object to hold both the email and password. Why do we create an object? Well, the reason is simple. We need to send those two pieces of information at once to the backend so it's easy for us to add them for a specific user. Since We are using fetch to post/send data somewhere we need to tell it what it should do with our data. First, we want it to post our data then we want the data to be stringified. That is convert the data to JSON. We are wrapping the code inside a try-catch block to help handle errors. If you look at the fetch() keyword you'll notice a URL inside the curly braces. That URL is going to be our backend URL. That is where the data from the form is sent to. We'll be creating our backend now.

Setting up our express-server

The first thing we need to do is create a new directory called server (It could be named anything). Change directory to this new server directory. once inside, run this command npm init this will set up our package.json file. Inside this file, we'll be able to see all the dependencies we use/need. The next thing we need to do is install the dependencies we'll need. For this particular task, we'll only be needing three things. One is CORS and the other is Express and the last is Nodemon. CORS is going to allow us to send the data across servers and Express will help us create our server quickly.
By now your app structure should look like this.
Alt Text

We'll now run this command, npm install express cors nodemon.
Note- It's good practice to install Nodemon as a dev dependency.
Once we've installed all the needed dependencies We need to set our start script so we can use npm start to just start our server with Nodemon. Open your package.json file and add this

"start": "nodemon index.js"
Enter fullscreen mode Exit fullscreen mode

just below the test line in the package.json file.

Server Code

We'll be adding the code below to our index.js file in our server directory.

const express = require("express");
const cors = require("cors")
const port = 5000
const app = express()

app.use(cors())
app.use(express.urlencoded({ extended: false }))
app.use(express.json())


app.post("/", (req, res)=>{
   const {email, password} = req.body
   console.log(`Your Email is ${email} and your password is ${password}`)
})

app.listen(port, ()=>{
    console.log(`server is running on port ${port}`)
})
Enter fullscreen mode Exit fullscreen mode

Code explanation

So this is a pretty simple server-side code base. We have a simple post-end point that console.log's the data sent from the front-end.

Let's run the application

So make sure you have your react front-end running and then simply type npm start in your server directory to boot up your server. Once your server is up and running, go to your front-end and enter the data you want to be sent to the backend like this (See gif below).
Alt Text

Conclusion

There you go. You now know how to post data from your client-side to your server-side. In my next post, we'll be setting up authentication and authorization with JWT, Cookies, and a SQL database. In that post, I'll be showing you how to fetch and use data from a custom-made API.

Top comments (0)