How to connect your Node/express Backend with your react Front-End(POST)
Tags: react, node, webdev
Published: 2021-05-06 21:18:53

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
<ol>
<li>You have some understanding of react and react hooks</li>
<li>You know how to set-up a basic express server</li>
<li>You Know about the fetch API</li>
<li>You Know about JSON</li>
</ol> 

#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.
```javascript
npx create-react-app app-name
```
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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/msx2jlabpvmnmc5aj63k.png)
We are going to open our `src` folder and change the contents of the `App.js` file to this 
```javascript
import  React from 'react'

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

export default App;
```
*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.
```css
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;
}
``` 
Your form should look like this 
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sho2zxrvcsxzsps12rai.png)
## 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 <a href="https://www.javatpoint.com/react-hooks#:~:text=Hooks%20are%20the%20new%20feature,lifecycle%20features%20from%20function%20components.&text=Also%2C%20it%20does%20not%20replace%20your%20knowledge%20of%20React%20concepts.">javatpoint</a>. 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. 

```javascript
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;
```
## 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 
```javascript
 const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
```
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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i3avqqu93dvca1lv8feq.png)

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 ```javascript
"start": "nodemon index.js"
```
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.

```javascript
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}`)
})
```
## 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rrr6iycfgt447eb500xs.gif)

# 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.