Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
February 25, 2021 01:15 am GMT

How to connect your Client side to your Server Side Using Node and Express.

Ever wondered how data is passed from your front-end (HTML, CSS, and JavaScript) to your back-end? Well, wonder no more. I'll be showing you a simple setup on how this is done.

Pre-requisite

1) You know your HTML
2) You have a basic understanding of Node.js (it's okay if you don't. Click Here to learn the basics of Node.js and its basic setups.)
3) Have some understanding of asynchronous programming.
4) Have Node.js on your computer.
Note: Download Node.js from the official website Here. Make sure to download the one that has the LTS on it. The installation is pretty straightforward. Just click next till its done.
5) Have some understanding of Linux terminal commands. (I'm guessing you probably have some sort of Linux terminal like Git Bash Installed)

Front-End Setup

I like to separate my client from my server-side so it's easier to deploy my application. You can create an empty folder on your desktop (You can name it anything. I named mine testapp) and then open it on your IDE and create a folder named client. Inside the client folder, we are simply going to create 2 HTML files. One called Login and the other signup. You should have something like thisAlt Text Inside the login.html, we'll do this inside. In the signup.html, we'll do the same except we'll add an additional input with a name attribute of "fullname".
Alt Text
code explanation: Now looking at that picture, you'll notice a couple of things. The form element is wrapped around the input element and the form element is given the action attribute and method attribute. What do those attributes do? Think of the action attribute as a guide, that directs the user's inputs or requests to the proper server-side route. It just carries the information to the appropriate spot on the server. Now let's talk about the method, what is that? The method just describes what kind of action the user is performing. There's the POST, GET, DELETE, PUT, and PATCH methods. Say the user wanted to click a button to get some information that would be a GET method or if they wanted to delete an item from their list then that would be a Delete method. If they wanted to update everything in their list, they would use a PUT method but if they only wanted to update selected fields in their list, they would use a PATCH method. for this tutorial, The user is trying to login into their account and that means that they need to send their data across to our servers, and as such a POST method is used. If you also look at the input elements, you'll see that we have a name attribute attached to it. What does that do? It is used to reference the form-data after submitting the form.

Back-End Setup

For our server-side, we'll be using Node.js and Express a Node framework to spin up our server. So let's begin. We'll First create a folder called server in the root directory. change directory into the server folder by typing cd server. You should have something like this.Alt Text

Note: yours will look a little different. The reason my file path looks like that is because my testapp folder is in a folder called Learning Materials. Don't worry this will not affect your code.

Setting up dependencies

Since we are inside our server folder, we'll be typing npm init inside the terminal. Just press enter on all the prompts presented. This will create a "packge.json" file. This file will hold the dependencies our server will need to function. Once that's done, we'll then run another set of commands. In your terminal, type npm install express cors body-parser nodemon. These commands will install node modules along with those dependencies into your server. Your package.json file should look like thisAlt Text

Setting up server file

Next thing we need to do is create the actual file that will get get our server up and running. Make sure you are still inside your server folder. Next create an index.js. Now we'll add the following code inside it.

const express = require('express')const app = express()const bodyParser = require('body-parser')const cors = require('cors')const port = 3000// We are using our packages hereapp.use( bodyParser.json() );       // to support JSON-encoded bodiesapp.use(bodyParser.urlencoded({     // to support URL-encoded bodies extended: true})); app.use(cors())//You can use this to check if your server is workingapp.get('/', (req, res)=>{res.send("Welcome to your server")})//Route that handles login logicapp.post('/login', (req, res) =>{    console.log(req.body.username)     console.log(req.body.password) })//Route that handles signup logicapp.post('/signup', (req, res) =>{console.log(req.body.fullname) console.log(req.body.username)console.log(req.body.password) })//Start your server on a specified portapp.listen(port, ()=>{    console.log(`Server is runing on port ${port}`)})
Enter fullscreen mode Exit fullscreen mode

Code Explanation: Remember those dependencies we installed earlier well we need to use them inside our index.js file. We need to import them into the file. We do that by requiring them and assigning them to a variable for easy use. You can name the variables anything but it's widely accepted to name them as you see here.

const express = require('express')const app = express()const bodyParser = require('body-parser')const cors = require('cors')const port = 3000
Enter fullscreen mode Exit fullscreen mode

What do those dependencies do? Good question. The first dependency is express. Express makes it easy to create a server with node without typing many lines of code. We first need to import it and then assign it to a variable called app that way we can easily use it anywhere. The next one is body-Parser. it is responsible for parsing the incoming request bodies in a middleware before you handle it. CORS(Cross-Origin Resource Sharing) Since our front-end and back-end is going to be on different servers, we need something that allows them to share data since browsers do not allow this for security reasons. We have a variable called port with a value of 3000(You can give your port any number). This is where our backend server will be. The last dependency is nodemon. This simply helps us to detect changes made in our server script and updates our server. Think of it as the live server for backend development. The next couple lines are of us just using the various packages we installed.

// We are using our packages hereapp.use( bodyParser.json() );       // to support JSON-encoded bodiesapp.use(bodyParser.urlencoded({     // to support URL-encoded bodies extended: true})); app.use(cors())
Enter fullscreen mode Exit fullscreen mode

The lines below describe our routes. The routes are where the users will send their login and signup information to and it's here we will either save the information and then respond to the user by signing/logging them in.

//Route that handles login logicapp.post('/login', (req, res) =>{    console.log(req.body.username)     console.log(req.body.password) })//Route that handles signup logicapp.post('/signup', (req, res) =>{console.log(req.body.fullname) console.log(req.body.username)console.log(req.body.password) })
Enter fullscreen mode Exit fullscreen mode

Here, we simply tell express to set up our server on the port we specified earlier.

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

Let's Visualize

So to check if our setup is working, we need to start both servers. first, let's run our client. Since all we have are 2 HTML files, you can just run it with live server. This should open the HTML file onto your browser. Next, we need to run our backend server. Make sure you are still in your server directory/folder and then type nodemon index.js. This should open up your server on port 3000 or whatever port you specified. You should get something like this in your terminalAlt Text Remember we left this

//You can use this to check if your server is workingapp.get('/', (req, res)=>{res.send("Welcome to your server")})
Enter fullscreen mode Exit fullscreen mode


in our codebase to test if the server is functioning. Simply open up your browser and type http://localhost:3000. You can replace the 3000 with whatever port number you used and you should see the "Welcome to your server" message inside the browser. You should see thisAlt Text

Testing time

Before we start sending requests from the front-end to the server/backend, we need to make sure we specify where we are sending the information. Open up your client folder and click open both signup.html and login.html. Remember the action attribute on the form element we described earlier, well, we are going to add http://localhost:3000/signup which leads to our server signup route. You should have this for signup.html
Alt Text and this for login.htmlAlt Text
Now that's done, you can go to either the signup.html page or the login.html page enter some information in the input like this,Alt Text
press enter and whatever you entered on the frontend will show up in your terminal like thisAlt Text

As you can see, the data we entered into our front-end shows up in our backend. We only console. logged the data. You could store the data in some database, respond to the signup attempt with a dashboard page, etc. If you've got any questions, feel free to ask in the comments below.


Original Link: https://dev.to/gbudjeakp/how-to-connect-your-client-side-to-your-server-side-using-node-and-express-2i71

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To