ther routes like so:</p>
<figure id="00d3">
<div>
<div>
<iframe class="gist-iframe" src="/gist/HussainArif12/5eb9e404c4122bf76a82cd7ac6e9964f.js" allowfullscreen="" frameborder="0" height="undefined" width="undefined">
</div>
</div>
</figure></iframe></div></div></figure><p id="7692">Let’s say the client is at the root homepage( <code><b>/</b></code> ) then the word <code><b>`at root`</b></code> will be printed out. Otherwise, if the client is at URL named <code><b>hussain</b></code> then the words <code><b>at URL named: Hussain</b></code> will be printed out.</p><p id="f53c">Run the code with a command <code><b>node express-routing-example</b></code></p><p id="eb94">Then on another command line write:
<code><b>curl localhost:3000</b></code> Here, the words <code><b>at root</b></code> will be printed
<code><b>curl localhost:3000/hussain</b></code> Here, the words ‘at URL named: Hussain’ will be printed. The words after<code><b>‘/’</b></code> is placed is the argument</p><h1 id="ffb7">POST Requests</h1><p id="4fd2">You can also handle other requests like POST, PUT, etc. To do so, just replace <code><b>app.get</b></code> with <code><b>app.post</b></code> or <code><b>app.put</b></code> with the same exact parameters</p><p id="546f">To handle POST requests:</p>
<figure id="89f5">
<div>
<div>
<iframe class="gist-iframe" src="/gist/HussainArif12/f1b0e2fbdc365c9331f7ffdceedb89ae.js" allowfullscreen="" frameborder="0" height="undefined" width="undefined">
</div>
</div>
</figure></iframe></div></div></figure><blockquote id="bde4"><p>Note: <code><b>app.use()</b></code> is a middleware function which will be discussed in coming article.</p></blockquote><p id="7efe">Execute the code through the command line, and then, to send data through cURL, open another terminal window to write:</p><p id="5a31"><code><b>curl -d 'Hello World' localhost:3000/ -H 'Content-Type: text/plain'</b></code></p><div id="a61e"><pre>curl -d <span class="hljs-symbol">'Hello</span> World <span class="hljs-keyword">at</span> hussain' localhost:<span class="hljs-number">3000</span>/hussain -H <span class="hljs-symbol">'Content</span>-<span class="hljs-keyword">Type</span>:text/plain' </pre></div><p id="97ba">Go back to your server terminal (previous terminal where cURL functions aren’t used) and notice that the data you sent has been printed in the window.</p><blockquote id="42ca"><p>Note : <code><b>-H</b></code> is used to specify the header to tell Express that the data that we are sending will be plain text. Express is very picky on the format which is why we have to specify the header before sending data</p></blockquote><h1 id="f5f4">Configuring Express</h1><p id="2f6b">You can change settings in Express on the fly. There are many configurations. Some of them being</p><div id="3357"><pre><span class="hljs-keyword">app</span>.<span class="hljs-keyword">set</span>(‘port’, process.env.PORT || 3000) <span class="hljs-comment">//change default port</span>
<span class="hljs-keyword">app</span>.<span class="hljs-keyword">set</span>(‘views’, ‘templates’) <span class="hljs-comment">// The directory the templates</span>
<span class="hljs-keyword">app</span>.<span class="hljs-keyword">set</span>(‘<span class="hljs-keyword">view</span> engine’, ‘jade’) <span class="hljs-comment">//set view engine to JADE</span></pre></div><h1 id="e24f">Express Application Generator</h1><p id="905c">The <code><b>express-generator</b></code> module is used to get templates for your website. This is done so that you-the developer, can spend less time in developing the design of the application as you already have the ‘skeleton’ of the website.
You can jumpstart your Expre
Options
ss development because the generator will create files and folders for different template engines and libraries.</p><p id="d151">This way, you can spend more time developing your backend logic properly.</p><h2 id="12c6">Getting started</h2><p id="2a1c">Run the command to install the module:</p><div id="2d2d"><pre><span class="hljs-attribute">npx express-generator</span></pre></div><h2 id="a5c6">Creating a project</h2><p id="c3fc">Now that we’ve installed the module</p><p id="57df">Run the commands:</p><div id="1297"><pre>express myProject <span class="hljs-comment">#create a project with name of myProject</span>
cd myProject <span class="hljs-comment">#change working directory to myProject</span>
<span class="hljs-built_in">npm</span> install <span class="hljs-comment">#install all required dependencies</span>
<span class="hljs-built_in">npm</span> start</pre></div><p id="45e5">We’re done!</p><p id="2eac">Working in your Express project directory, you might have noticed further subdirectories and files. Here is an explanation</p><ul><li><code><b>app.js</b></code>: the main file, houses the embedded server and application logic</li><li><code><b>/public</b></code>: contains static files to be served by the embedded server</li><li><code><b>/routes</b></code>: houses custom routing for the REST API servers (not needed for a web app)</li><li><code><b>/routes/users.js</b></code>: endpoint/routes for resources such as users</li><li><code><b>/views</b></code>: contains templates that can be processed by a template engine (not needed for REST APIs)</li><li><code><b>/package.json</b></code>: project manifest</li><li><code><b>/www</b></code>: boot up script folder</li></ul><blockquote id="ebe7"><p>Note: a web app is a traditional web application (thick server) with 100% server-side rendering while a REST API is a data only server (rendering happens and UI is hosted on the clients)</p></blockquote><h1 id="578d">Summary</h1><h2 id="05e1">To install express</h2><div id="8dbe"><pre><span class="hljs-built_in">npm</span> i express</pre></div><h2 id="e934">To handle requests:</h2><div id="e5f2"><pre>app.<span class="hljs-keyword">METHOD</span>(route, <span class="hljs-keyword">handler</span>)</pre></div><p id="7e13">where</p><ul><li><code>METHOD</code> can either be <code>put</code>, <code>get</code> ,<code>post</code> or <code>delete</code></li><li><code>route</code> will be your path</li><li><code>handler</code> will be the callback function that’s executed whenever this route is handled.</li></ul><h2 id="825c">To configure:</h2><div id="65ec"><pre>app.<span class="hljs-built_in">set</span>(<span class="hljs-built_in">key</span>,itsValueToChange)</pre></div><h1 id="dfa6">External Resources</h1><ul><li><a href="https://developer.mozilla.org/en-US/docs/Learn/Server-side/Express_Nodejs/skeleton_website">Creating a skeleton Website — Mozilla</a></li><li><a href="https://expressjs.com/en/starter/basic-routing.html">Express Basic Routing</a></li><li><a href="https://www.creativebloq.com/how-to/get-started-with-expressjs">Get Started with Express.JS</a></li></ul><p id="8c3c">In the coming articles, we will go more in-depth to Express and its workings. That’s all for today. Thank you so much for reading!</p><p id="d73b">Stay home, stay safe!</p>
<figure id="b8ea">
<div>
<div>
<img class="ratio" src="http://placehold.it/16x9">
<iframe class="" src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2Fc36271%3Fas_embed%3Dtrue&dntp=1&display_name=Upscribe&url=https%3A%2F%2Fupscri.be%2Fc36271&key=a19fcc184b9711e1b4764040d3dc5c07&type=text%2Fhtml&schema=upscri" allowfullscreen="" frameborder="0" height="400" width="800">
</div>
</div>
</figure></iframe></div></div></figure></article></body>
Use Express.JS as a Web Server
In this article, we will learn about Express.JS for handling POST and GET requests, and why it’s more suitable than the http core module of the Node.JS engine.
What is Express and What Makes It So Great?
Express is the most popular Node.JS framework to handle multiple different HTTP requests at a specific URL. Furthermore, it’s minimal, open-source, and flexible which aids the developer to invest less effort and time into developing even better websites and apps.
With tech giants like Uber and Twitter using it, surely it must be an amazing tool. It adds dead-simple routing and essentially shortens the lines of code that is needed to handle web requests.
Let me illustrate an example:
Reusing the code from my previous article:Use Node.JS as a Web Server, here is an example using the http module in NodeJS
Now let’s rewrite this using the Express API:
Getting Started
Install it through NPM. This is a straightforward step. For more help on NPM, I’ve written a guide here
npm i express
You’re now good to go!
Simple Example
Let’s write a GET method in Express to display the words ‘Hello World’. Reusing the code from the above example:
Run the code through the command line node express-basic-hello-world , and then on another command line, type:
curl localhost:3000
The first parameter of app.get() is the route.
The second parameter is the callback, as explained in the previous heading
app.listen tells us the port number it will respond to.
What’s routing? Routing refers to how an application’s endpoints (URIs) respond to client requests
If the client is at URL or route ‘/’(in other words, the root homepage), then execute the block of code located within the callback. Fairly easy!
Handling Other Routes
You can even handle other routes like so:
Let’s say the client is at the root homepage( / ) then the word `at root` will be printed out. Otherwise, if the client is at URL named hussain then the words at URL named: Hussain will be printed out.
Run the code with a command node express-routing-example
Then on another command line write:
curl localhost:3000 Here, the words `at root` will be printed
curl localhost:3000/hussain Here, the words ‘at URL named: Hussain’ will be printed. The words after‘/’ is placed is the argument
POST Requests
You can also handle other requests like POST, PUT, etc. To do so, just replace app.get with app.post or app.put with the same exact parameters
To handle POST requests:
Note: app.use() is a middleware function which will be discussed in coming article.
Execute the code through the command line, and then, to send data through cURL, open another terminal window to write:
curl -d 'Hello World at hussain' localhost:3000/hussain -H 'Content-Type:text/plain'
Go back to your server terminal (previous terminal where cURL functions aren’t used) and notice that the data you sent has been printed in the window.
Note : -H is used to specify the header to tell Express that the data that we are sending will be plain text. Express is very picky on the format which is why we have to specify the header before sending data
Configuring Express
You can change settings in Express on the fly. There are many configurations. Some of them being
app.set(‘port’, process.env.PORT || 3000) //change default portapp.set(‘views’, ‘templates’) // The directory the templatesapp.set(‘view engine’, ‘jade’) //set view engine to JADE
Express Application Generator
The express-generator module is used to get templates for your website. This is done so that you-the developer, can spend less time in developing the design of the application as you already have the ‘skeleton’ of the website.
You can jumpstart your Express development because the generator will create files and folders for different template engines and libraries.
This way, you can spend more time developing your backend logic properly.
Getting started
Run the command to install the module:
npx express-generator
Creating a project
Now that we’ve installed the module
Run the commands:
express myProject #create a project with name of myProject
cd myProject #change working directory to myProjectnpm install #install all required dependenciesnpm start
We’re done!
Working in your Express project directory, you might have noticed further subdirectories and files. Here is an explanation
app.js: the main file, houses the embedded server and application logic
/public: contains static files to be served by the embedded server
/routes: houses custom routing for the REST API servers (not needed for a web app)
/routes/users.js: endpoint/routes for resources such as users
/views: contains templates that can be processed by a template engine (not needed for REST APIs)
/package.json: project manifest
/www: boot up script folder
Note: a web app is a traditional web application (thick server) with 100% server-side rendering while a REST API is a data only server (rendering happens and UI is hosted on the clients)
Summary
To install express
npm i express
To handle requests:
app.METHOD(route, handler)
where
METHOD can either be put, get ,post or delete
route will be your path
handler will be the callback function that’s executed whenever this route is handled.