DEV Community

Cover image for Node Express
Barrington Hebert
Barrington Hebert

Posted on • Edited on

Node Express

      One of Node.js's most popular and well-known frameworks is Node Express. Node Express, is used primarily for building server-side web applications and APIs and is the_ most _popular framework for Node. With Node Express, we can simplify the process of handling HTTP requests and response.

Image description

Let's Get Started With Node Express!

      Unlike it's 'opinionated' counterparts; which tend to have a plethora of rules and conventions that need to be followed, Node Express is considered 'unopinionated', meaning it caters to different ways to accomplish the same tasks. It includes the bare necessities and helps us as programmers structure our folders the way we want. If you never heard of Node Express then you have come to the right place! I have traversed the myriad of Node's profound glossary of documentation to figure out just enough to get you started with Node Express. So without further ado, let's get you started! *(Note that I am presuming you have node already installed and set from their website: https://nodejs.org/en/download/package-manager and also that you have your package.json... but if you don't, no need to worry; just type this into your terminal: *npm init -y).

Image description

First things, first; open up your terminal and type in the magic words:

npm i express
Enter fullscreen mode Exit fullscreen mode

Now you have node express installed! Crazy! Okay, let's step it up, you are going to want to import your fresh and new node express into your code like so:

const express = require('express');

const app = express();
Enter fullscreen mode Exit fullscreen mode

      Ah, so up on line 1 we import our node express using require, a node module syntax. The next thing people usually will do is assign express to a variable; I am using the word app because it is the industry standard. Now that we are armed to the teeth with Node Express ready to fire; lets build a basic server by adding our quintessential listen method.

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

      Now I will say this; it is important that you say precisely "Server is running on port xxxx", these are the magic words of the Node Express Empire. So it may come in handy to set up some variables for your port like so: PORT = 8080 Anyways; lets throw in a get request:

Node Express And Request Handlers

const express = require('express');

const app = express();

let PORT - '8080';

app.get('/', (req, res) => {
res.send('Hello World');
});

app.listen(8000, () => console.log(`Server is running on port ${PORT}`));


Enter fullscreen mode Exit fullscreen mode

      The cool thing about this get request is the fact I am using res.send(). Res and Req are our requests and response objects that we receive from the server; by using app.get; I make it clear that this is for a get request, and the first parameter is the data, or URL that is being requested. With res.send(), I am using the send method on my response object, if I wanted to; I could also put html tag or even an object directly into it's parameters and it would still work; like so:

//with html tag
res.send( `<h1> HELLO WORLD <h1>` )

//JSON
res.send({ message: 'Hello World' }) 

Enter fullscreen mode Exit fullscreen mode

      Now 1 request is never enough; we can add as many as we want; a collection of request handlers together is usually referred to as routers. But let's focus more on the wonders of express. The old way of doing things is placing a bunch of routers together. Lets say we have our index.html file, and another html file called 'about.html'. We can use the sendFile method on our response object to send our user directly to this page by simply passing in the directory into the method.

const express = require('express');
const path = require('path');

const app = express();

let PORT - '8080';

app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'index.html'));
});

app.get('/aboutMe', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'aboutMe.html'));
});

app.listen(8000, () => console.log(`Server is running on port ${PORT}`));

Enter fullscreen mode Exit fullscreen mode

      So this is the old way of doing things; with Node, bringing in the path module; then pointing to the directory that has your file using __dirname. Feel free to simmer on the syntax:
path.join(__dirname, *A Folder Name*, *Another Folder Name*, *The File to load*)
      Take note of that extra get request that I threw in there. Don't panic but now that we have two get requests; you're technically looking at a router at this point, we are 'routing' them with a proper response, and our second get request is responding to our user to a separate page based on the request. The syntax of node express tries its personal best to make this obvious. The sweet language Gods of code languages blesses us once again by giving us a language that is easy on the eyes. If one is able to recognize objects, methods, and functions, within basic JavaScript syntax, then you can see all of what Express truly is: a list of spells to be wielded by the proper sorcery. These spells can be understood through dwelling within the Node Documentation Spell library. In which the Spells must be announced following the same proper sorcery and grammatical practices.

Image description

So in the real world; there may be thousands of directories and files. But Express comes in a form of something that I like to call, destructuring for folders. Pretty much that whole code block can be summed up to a few lines using the express static middleware. app.use.

const express = require('express');
const path = require('path');

const app = express();

let PORT - '8080';

app.use(express.static(path.join(__dirname, 'public')));


app.listen(8000, () => console.log(`Server is running on port ${PORT}`));

Enter fullscreen mode Exit fullscreen mode

      This 1 line will still enable you to have a successfully running website without needing to type out every single file address. Now you can create more html files inside of your folder, and they will still work (granted you have to type in .html at the end). But this is one of the many gifts of node express.

Image description

      There are multiple shortcuts afforded to us with node express, and as I said earlier, it is unopinionated. Another way of shortening the code is by creating another folder and placing all of our routers in there; request handler style!

Say you have a folder that contains a javascript file that looks something like this:

const express = require(express)
const router = express.Router()

///all your get and post requests can by copied and pasted into here 
router.get('api/posts/', callback())
Enter fullscreen mode Exit fullscreen mode

Notice we are using express.Router()? Which means all our requests syntax will change from app.get() to router.get(*folder directory*, *callback*). They will still have the same functionality;
you can go back to your main server file; and just put in

//all your requirements aka imports here//
const posts = require('/folderPath/posts');

const app = express();

app.use('/api/posts', posts);

app.listen( etc )


Enter fullscreen mode Exit fullscreen mode

      Notice something different? We can utilize app.use() to designate we want to use certain files for items in our other folder. The syntax looks like this:
app.use('directory to a file as a string', variableToBeUsed), In this case, our first parameter dictates an endpoint we want to use, and the variableto BeUsed will be available inside your main server file after importing it; doing this removes the need to pass in the entire folder directory on your get request; and thus shortens the length of your get requests in your routers to this: router.get('/', callback)).

A BRIEF Touch on MiddleWares

      So now that you know the basics (you're welcome) lets briefly discuss the most important aspect of node express; which is middleware. Along your journey into Node Express, you will hear the word 'middleware' thrown around like candy; don't be frightened. It is essentially a fancy way of describing all the code that runs during the time your routers are running... Meaning it is the code that happens during the time a request is being handled from a client. It is the time in the middle; before the site responds; while the page loads; the twilight zone of coding. Let's say there is a function that provides updates in the log as to which programs are running or which callbacks are being successful; whilst checking for errors. These functions are called 'loggers' and are a type of middleware you will soon experience along your journey of understanding how node works.

Image description

Conclusion

      With that being said; I hope you all are enjoying Node Express as much as I am; at first it may seem to be a huge jump from NodeJS, but it is more of a different way of doing things. Hopefully I spared you from the vast caverns of the Node documentation libraries, and have allowed you time to reconcile on the beauties of Node Express. -Cheers

Top comments (0)