Wednesday, May 9, 2018

How to setup express.js and execute server to display static content

1- Create a server.js file
2- In console, install node
npm init --yes
3- In console, install express framework
npm install -s express
where -s indicates this should be registered as a dependency
4- Next, go back to the empty server.js file and create the express library variable
var express = require('express')
5- Now, create the variable for the express object
var app = express()
6- Now, add the code that will turn on the server upon execution of the app
app.listen(3000)
and run in the console: nodemon ./server.js
7-  In your browser, head to http://localhost:3000/ this will give you a 404 error in the console (see network tab). This is because no data was sent to the server
8- For example purposes, in the same dir, let's create an index.html file and add the text/string:
hello
9- Back in server.js, instruct the app to read static files from the same directory
app.use(express.static(__dirname))
10- Now, let's adjust the app.listen(3000) event to include the html to be delivered by the server:
var server = app.listen(3000, () => {console.log('server is listening on port', server.address().port)})

In simple terms, here, you:
  1. Installed node and express framework dependencies
  2. Called express library and object
  3. Server needs to display data, because of this, create the content to be displayed
  4. Instruct the app where to read the data from
  5. Instruct the app to execute server
  6. Server displays the data

No comments:

Post a Comment