What is Express?
Express. js is a Node. js web application server framework, designed for building single-page, multi-page, and full stack web applications. It is the standard server framework for node.
Let’s start by creating a new directory. I’m going to call mine “blogExpressApp” for the sake of this demo. Next, let’s cd (change directory) into our new project folder and run
npm init.This creates a
package.json file where we can install Express. Just hit enter through all the prompts that appears.
Running Node for the first time in your life
The simplest way to use node is to run the
node command, and specify a path to a file. Let’s create a file called
server.js to run node with. Here we are going to set up the skeleton to our app. Run
touch server.js in the terminal to create this file.
In a moment we’re going to run our app. Let’s first add a console.log() in our server.js file.
Lets run our app with the command
node server.js You should see the console.log in your terminal!
First, we have to install Express. We can do this by running the
npm install command (
npm stands for Node Package Manager and is installed with Node, which is why we used a command like
npm init earlier).
npm install express --save command in your command line.
Great, Express should now be installed. Next, we use express in our
server.js file by requiring it.
We need to create a server that browsers can connect to. Let’s create a variable called port and set it to 5000. Next, we’re going to use Express’s
Lets run our app again with the command
node server.js You should see the console.log in your terminal! In addition, this means our app is running! However, if we navigate to localhost:5000 in the browser we should see a message saying “cannot GET /”. This is where we can begin defining our routes. To keep this app simple, we’re going to set up just a simple GET request for reading information. Now, we’re going to use Express’s
Our methods first argument takes a path. In this app, we’re defining a route of “/”. Our method’s second argument is a callback function which takes a request and response argument. Now when we navigate to localhost:5000/ we’re telling our app to respond with “Hello World”. Check it out!
Let’s take this app’s complexity up just one more level. Let’s create another file called index.html. We’re going to instead send an HTML file as a response instead, in the next step.
Back to our app.get() method, instead of sending back hello world, lets send our HTML file as a response!
Let’s run our app one last time with the command
node server.js and navigate to localhost:5000/.
You’ve officially created your very own Express. js app!
Below I’ve added a link to really helpful resource that gave me a really great understanding for the Express JS basics. Good Luck! The world is yours, take your knowledge and keep spreading it.