DEV Community

Sebastian Gbudje
Sebastian Gbudje

Posted on

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 it’s 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 here
app.use( bodyParser.json() );       // to support JSON-encoded bodies

app.use(bodyParser.urlencoded({     // to support URL-encoded bodies
 extended: true})); 
app.use(cors())

//You can use this to check if your server is working
app.get('/', (req, res)=>{
res.send("Welcome to your server")
})


//Route that handles login logic
app.post('/login', (req, res) =>{
    console.log(req.body.username) 
    console.log(req.body.password) 
})

//Route that handles signup logic
app.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 port
app.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 here
app.use( bodyParser.json() );       // to support JSON-encoded bodies

app.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 logic
app.post('/login', (req, res) =>{
    console.log(req.body.username) 
    console.log(req.body.password) 
})

//Route that handles signup logic
app.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 working
app.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.

Discussion (9)

Collapse
behranm profile image
BehranM

I have a simple node.js/mysql app. I have followed every step in your tutorial but nothing works. I can't even get past the variable declarations via require. No matter what I do, I keep getting errors. I don't know how you get yours working because browser and node are two different servers/ platforms and node functions such as require are not recognized by the browser. To get around this, I have installed Browserify but it led to other errors. I am so sick of this incompatibility between the browser and node environments that I am about to give up. I have tried asking for help in stack overflow forum, everyone says something else which I have tried but so far it is nothing but extreme frustration. Several people said that I need to use AJAX to make requests to node server because I can't start a tcp server in the browser. But I don't see any AJAX calls in your example and you claim that it works.

Collapse
trancephorm profile image
pyc • Edited on

Feeling your frustration completely because I've gone through same frustration until I realised I need something like Parcel (parceljs.org/). Just go through Getting Started section and then you'll realise you can build apps using NPM modular system, and they will work in browsers because Parcel will pack them for that environment. Generally, as far as how I understand it's best is that you definitely separate client and server code into 2 projects. Parcel is optimizing client code, and Node.js is dealing with server code. Node.js as an environment has nothing to do with web browser clients which for example have DOM (Document Object Model) model which Node.js lacks.

I was foolishly trying to make IndexedDB work in Node.js, which is even (kind of) possible if you use fakeIndexedDB (github.com/dumbmatter/fakeIndexedDB), but that code works only on the server side, and by the way it's not a complete IndexedDB implementation in Node.js. You can't see that fake IndexedDB in your browser, it stores its data on Node.js's server memory.

Node.js server code serves only raw data in whatever format you want, web client uses it for obtaining data, but renders it however you want in the web browser.

All in all, it took some time for me to understand NPM (Node Package Manager) is actually completely independent or better say actually unrelated to Node.js.

Still I'm pretty new to all of this, and I would like someone to fix my view on this if I misunderstood it, but I doubt.

Collapse
zippytyro profile image
Shashwat Verma

Simple and easy. Should nodemon be in devDependencies instead in the main ones?

Collapse
gbudjeakp profile image
Sebastian Gbudje Author

Yes, you are right. Nodemon should always be in dev dependencies. I didn't put it there because I didn't think it necessary but I'll be editing that in. Thanks for the observation.

Collapse
camus1859 profile image
Anderson Laventure

Earlier versions of Express used to have a lot of middleware bundled with it. bodyParser was one of the middleware that came with it. When Express 4.0 was released they decided to remove the bundled middleware from Express and make them separate packages instead. The syntax then changed from app.use(express.json()) to app.use(bodyParser.json()) after installing the bodyParser module.

bodyParser was added back to Express in release 4.16.0, because people wanted it bundled with Express like before. That means you don't have to use bodyParser.json() anymore if you are on the latest release. You can use express.json() instead.

stackoverflow.com/questions/472321...

Collapse
kleguizamon profile image
Kevin Leguizamon

Great post!!

Collapse
ra1nbow1 profile image
Matvey Romanov

Simple guide. Thank you

Collapse
poglolree profile image
poglolree

how do you send a variable back to the client side?

Collapse
seck_mohameth profile image
Mohameth Seck

So simple and quick to follow. Thanks for this!