express_setup
This post will explain how to setup express and how to write a simple test route, that ensures the middle ware is properly setup.
The first step is to add our web framework, express…
at this point you can run the command “yarn add express ” and hit enter or…as a habit I always like to add the dependencies “body-parser” and “cors” at the same time as adding express….
Run the command “yarn add express body-parser cors”. Lets briefly touch on both body-parser and cors, but I recommend if these are completely new topics, take some time to understand exactly what both do.
Body-parser is the Node.js body parsing middle-ware. It does exactly what it sounds like it should, it parses all the incoming request bodies in a middle ware, before you handle it…
CORS stands for Cross Origin Resource Sharing, and it allows restricted resources from another domain outside the domain from which the first resource was served. But back to the task at hand!
The next step is to start your server. I use nodemon with a few custom scripts that allow me to start the server once and then to see all updates to the code without having to shut it down and save and start it up again.
After the server is started… go ahead and create an app.js file in you project… then we are going to import express from ‘express’; then go ahead and create a variable, I default to app…. set it equal to the invoked function express()… then we are going to use the listen method that comes with express will pass in the port we want to specify. In this case I default to 3000, then an anonymous callback function with console log to ensure it is actually listening.
If it is actually working you should see listening on port 3000… in the console.
Alrighty, we are just about there… last thing to do is too is to make sure to write a quick test route, if you type localhost:3000 into your browser, you should get an error…
Let’s fix that! Time to use another method that express gives us… app.get() is going to take place of an actual get request. We will first specify the our homepage which is indicate by ‘/’, then an asychnronous call back that takes two arguments, a request and a response, lets now just send our response using res.send(‘hello world’) with the obligatory hello world!
Now go back to the browser and refresh!
And there it is! We have successfully setup express and tested our route request and response.