What is Express?
A node framework, that was built to make programmers write less repetitive code
Built specifically for web developers
Creating Our First Server with Express
npm init npm install express In the server.js File //jshint esversion:6 Place this comment above to remove warnings const express = require(‘express’); Function that represents the express module, and gets binded to the variable app const app = express(); Listen to a specific port app.listen(3000);
Handling Requests and Responses: the GET Request
localhost:3000
Equivalent to the root of a home page
Root Page
Browser sends a GET request to the server
app.get(, )
Example
app.get(“/”, function(req, res) {});Understanding and Working with Routes
app.get(, )
Specifies the route that we are going to respond to
When a route is encountered, the get() is executed
Path
Example:
Root Path
“/”
Responds for the specifies Route
Example:
function(req, res) {
res.send();
Nodemon.io
Will monitor for changes in your js code and will automatically change your code
Activate nodemon
nodemon
Responding to Requests with HTML Files
res.sendFile() \_\_dirname Gives the current file path Usage: \_\_dirname + “”
Processing POST Requests with Body Parser
has an action and a method method POST, so we are sending data somewhere action Path/location to interact with (Like sending data via a POST)
app.post(, )
Specifies that when there is a POST request for the route, the callback method will be executed
body-parser
Used to parse incoming POST data
To install, call the command “npm install body-parser”
In the JS file, include
const bodyParser = require(‘body-parser’);
app.use(bodyParser);
body-parser Modes
app.use(bodyParser.)
bodyParser.text()
Parse all the requests into text/string
bodyParser.json()
bodyParser.urlencoded()
Used when parsing data that is sent via a HTML form
bodyParser.urlencoded({extended: true})
Allows us to POST nested objectsJavascript Starter Template
Please see the attached screenshot