18 KiB
Express Basics
JS HTTP server
A simple HTTP server in Node
A simple server in three steps:
include "http" library
create server responses
define the port that you want to listen to.
Note: The _ before a variable name is used to indicate that the variable isn't used. This is to avoid the VSCode warning about unused variable
import http from 'http'
const server = http.createServer((_req, res) => {
res.write('Some cool response!')
res.end()
})
const port = 3000
server.listen(port)
console.log('HTTP Server listening port', port)
For this code to work, remember "type": "module" in your package.json. Also, you may need to change your port number to something other than 3000.
PORT numbers
The port number (16 bit unsigned integer) defines a port through which the communication to your application happens. Ports allow multiple applications to be located on the same host (IP).
The client connects to this port in some server (defined by an IP address), so the client and the server are able to communicate.
Computers have several different ports at their disposal __ but __ some of them are being used and your application might not be able to assign those ports to itself.
Ports from 0 to 1023 are the system ports. There are restrictions in manually assigning applications to use them.
Generally speaking, ports from 1024 to 65535 are available for user to assign applications to use them.
Request and response
The request object is an object that is sent __ from the client to the server.__
The response object is an object that is sent __ from the server to the client__ . When you modify the response object, you're essentially modifying how the server responds to the client.
const server = http.createServer(( req , res ) => {
res.write("Some cool response!");
res.end();
});
Exercise 1: Simple Request & Response
Create a basic HTTP-server application. The application should respond to GET requests by returning a response with the following content: "Hello world!".
Test your application either with Postman, or by navigating your browser to http://localhost:< your_portnumber >
Solution: https://gitlab.com/bctjs/week3-day2/-/blob/master/examples/day2/countdown.js
Express Server
Express
Express is the most popular server-library for Node
Setting up a server with node-http is already fairly simple, but Express tries to make this even simpler
In some cases you can manage without Express, but for larger applications it's recommended
Install Express by using
npm install express
A side note about dependencies
- __By using __ npm install , the package will become dependency for the application.
- __By using __ npm install --save-dev , the package will become __ development dependency __ for the application.
- This means the package won't be included in the built application.
- __A shortcut for __ -- save-dev __ is __ -D
- Dependencies are needed to run the application, dev-dependencies are needed for development.
- __Additional info: __ https://www.geeksforgeeks.org/difference-between-dependencies-devdependencies-and-peerdependencies/
Getting started with Express
__Create a very simple express project __
import express from 'express'
const server = express()
server.listen(3000, () => {
console.log('Listening to port 3000')
})
Then start the server and connect to __ http://localhost:3000 __ with your browser. __ (See instructions on the next slide)_
Starting the server
__To make using the import statement possible, we need to edit the __ package.json.
Add a new script "start" with the value "node index.js" under "scripts" object in the package. json
_(you can name index.js to whatever file your server code is in)
Add "type": "module" property
__Now you can run the server with __ npm start
Express - Requests
__The server does not yet __ do __ anything except listens. That is because we have not defined how it should deal with incoming __ requests.
With Express you can easily process different kind of requests, e.g.,
server.get(), server.post(), server.delete() etc!
An example of a simple GET response below.
server.get("/", (request, response) => {
response.send("Just saying hello!")
})
Käy läpi tämä esimerkki, ja anna sitten tehtäväksi ensinnäkin muuttaa portti ja palautusviesti muotoon "Hello world!". Tällä tavalla kaikkien pitää ymmärtää miten tämä toimii. Anna heidän pähkäillä miten voi tehdä päätepisteen, johon pääsee näin localhost:5000/secondPage. Tämän jälkeen käy läpi yhdessä tämä heidän kanssa.
Express - Endpoints
__To create a new __ _endpoint _ __we define what __ kind __ of request we're handling, then what the __ route __ to the endpoint is and finally what the endpoint __ does .
__In the below example we are creating an endpoint that handles a __ GET __ request to route __ /foobar , that sends a response containing the string 'OK'.
server.get('/foobar', (req, res) => {
res.send('OK')
})
Nodemon
Reminder __: If you are not using Nodemon in development, you are making your life unnecessarily difficult. Use Nodemon. __
__Instructions are __ below as a refresher.
Nodemon with JavaScript
One of the handiest packages out there is nodemon, which monitors your node program. Whenever you save your files, it reloads the program, showing you immediately the results of your changes.
Nodemon is installed as a dev dependency npm install --save-dev nodemon
To use nodemon, you should have a development script "dev": "nodemon ./index.js"
Nodemon with TypeScript
To get Nodemon working with TypeScript we need additional package to run our TS code without waiting for it to compile. npm install --save-dev nodemon ts-node
After installing, nodemon works directly with .ts files. "dev": "nodemon ./index.ts"
Exercise 2: Simple Express Server
Create a basic Express application. The application should respond to GET requests by returns a response with the following content: "Hello world!".
Extra: Add a new endpoint to your application. So, in addition to accessing http://localhost:3000 , try to send something back from http://localhost:3000/endpoint2 .
Solution: https://gitlab.com/bctjs/week3-day2/-/blob/master/examples/day2/countdown.js
Request params & query
If request params are defined, they're something user __ must __ send to the server.
https://localhost:5000/ThisIsParam
Request query is __ optional __ information that the user can send to the server.
https://localhost:5000?ThisIsQuery=123
Chaining query parameters:
https://localhost:5000?first=123&second=456
Request params & request query
app.get("/:name/:surname", ( request , response ) => {
console .log("Params:");
console .log(request.params);
console .log("Query:");
console .log(request.query);
response.send("Hello " + request.params.name);
});
app.listen(5000);
Try connecting via browser!
localhost:5000 /John/Doe
localhost:5000 /John/Doe ?query1=123
Johdatteleva esimerkki vielä ennen seuraavaa tehtävää.
Request query & param types
__Request parameters and query parameters are always of type __ string __. If a number is passed, it will be a string that contains a number. __
__The example on right will __ __always __ __return 404, since the strict equality __ item.id === id
will never be true. This is because the __ item.id __ __is of type __ _number _ and __ id __ __being of type __ string .
import express from 'express'
const server = express()
const data = [
{ id: 1, name: 'John' },
{ id: 2, name: 'Jane' }
]
server.get('/:id', (req, res) => {
const id = req.params.id
const info = data.find(item => item.id === id)
if (info === undefined) {
return res.status(404).send()
}
res.send(info)
})
server.listen(3000)
Exercise 3: Counter Server
Create an API that consists of only one endpoint:
/counter
Whenever you enter this endpoint from the browser, it
should respond with a JSON object with information on how many times the endpoint has been accessed.
Extra: Make it possible to set the counter to whichever
integer with a query parameter /counter?number=5
Solution: https://gitlab.com/bctjs/week3-day2/-/blob/master/examples/day2/countdown.js
Exercise 4: Advanced Counter Server
Expand the API from the previous assignment by accepting a name through the counter endpoint: /counter/:name
When entering this endpoint, the server should return the count of how many times this named endpoint has been visited.
For example
Aaron enters /counter/Aaron 🠖 "Aaron was here 1 times"
Aaron enters /counter/Aaron 🠖 "Aaron was here 2 times"
Beatrice enters /counter/Beatrice 🠖 "Beatrice was here 1 times"
Aaron enters /counter/Aaron 🠖 "Aaron was here 3 times"
Solution: https://gitlab.com/bctjs/week3-day2/-/blob/master/examples/day2/countdown.js
"url" library
With the "url" library, you can parse url fields (i.e., requests) the client sends to your server.
import url from 'url';
// URL module usage example
const adr = ' http://localhost:5000/default.html?year=2017&month=february '; // Define the address
const q = url.parse(adr, true); // Parse through the address with url.parse() function.
console .log(q.host); // returns 'localhost:5000'
console .log(q.pathname); // returns '/default.html'
console .log(q.search); // returns '?year=2017&month=february'
const qdata = q.query; // returns an object: { year: 2017, month: 'february' }
console .log(qdata.month); // returns 'february
Express Middleware
Middlewares
__Generally speaking, middleware is an application that does something in between some other applications. __
There are tons of middleware libraries available for Express.
__What this means in Express: with a middleware, you can manipulate the __ __the client request and server response __ in the client-server communication.
Middleware __ functions are functions that have access to the __ request __ object (__ req ), the __ response __ object ( res ), and the __ next __ function in the application's request-response cycle. When the __ next __ function is invoked, the next middleware function is executed.
Middleware can be defined as such
const authCheck = (req, res, next) => {
if (req.headers.Authentication === undefined) { // Read the request object
res.status(401).send('Missing Authentication Header') // Modify the response object
} else {
next() // Execute the next middleware
}
}
In Express, .use() method initializes a middleware (argument 2) in a given path (argument 1).
In the middleware, the next() function will jump to the next middleware or endpoint.
server.use('/customers', authCheck)
server.get('/customers', (req, res) => {
// we know that Authentication header is present
...
})
Exercise 5: Logger Middleware
Create a new project called Student Registry. We will be developing this program in stages during this lecture. For now it should have a single GET endpoint /students that returns an empty list.
Create a logger middleware function that is used in all the project's endpoints. The middleware should log
the time the request was made
the method of the request
the url of the endpoint
Solution: https://gitlab.com/bctjs/week3-day2/-/blob/master/examples/day2/countdown.js
Middleware - Unknown endpoint (AKA 404)
As you might have noticed, all websites have some kind of a default functionality for unknown endpoints.
This can be handled with a middleware.
Unknown endpoint has to be taken into use after the actual endpoints!
Middleware - Error handler
An error handler is often needed to handle different kind of user or application errors.
We can use middleware to enable error handling for our application.
Has to be the last middleware to be taken into use!
Middleware - Req & Res
A n eed to manually alter req & res is quite common. To avoid bloated code, the handling can be easily done with proper middlewares.
Setting a header in middleware:
app.use((req, res, next) => {
res.setHeader('Content-Type', 'image/png')
next();
});
})
Getting a header and storing its value. If the header is not present, return 403 with an 'Unauthorized' message:
app.use((req, res, next) => {
const someIdNeededInApplication = req.header('Some-Custom-Header')
if (!someIdNeededInApplication) {
res.status(403).send('Unauthorized')
}
someIdFunctionality(someIdNeededInApplication)
next()
})
Exercise 6: 404 Not Found
Add a middleware function that sends a response with status code 404 and an appropriate error message, if user tries to use an endpoint that does not exist.
If you have not already done so, move all your middleware to a separate file, to keep your program clean and readable.
Solution: https://gitlab.com/bctjs/week3-day2/-/blob/master/examples/day2/countdown.js
Express.js: Creating a REST API
REST HTTP requests
We have gone through what a GET request is. Let's briefly go through what other types of requests are necessary for you.
GET /products/:id → Returns a single product identified by its id
GET /products →Returns all the products
POST /products → Creates a new product
DELETE /products/:id → Removes a single product identified by its id
PUT /products/:id → Updates an existing product
Basic RESTFUL functionality is often referenced as a CRUD (Create, Read, Update, Delete).
Handling request content
To properly handle some requests, e.g., POST requests, in Express, a body-parser middleware must be taken into use. It's as simple as:
const server = express()
server.use(express.json())
You might encounter a separate body-parser being used. This is no longer necessary, as Express 4.16+ includes a body parser middleware built-in.
express.urlencoded() allows us to parse url-encoded forms by attaching the data to the request body.
const app = express()
app.use(express.json())
app.use(express.urlencoded({extended: false}))
_The "extended" parameter's false value only says that we are not dealing with any complicated objects (objects with sub objects, etc)
Basic POST request
const app = express()
app.use(express.json())
app.use(express.urlencoded({extended: false}))
app.get("/", (req, res) => {
console.log("GET request init!");
res.sendFile(__dirname + "/index.html");
})
app.post("/", (req, res) => {
console.log("POST request init!");
console.log(req.body);
res.redirect("/");
})
Request Body
GET __ methods should not in general have body parameters. The GET method should only be used to get data, the request should not convey data. __
Despite this, most modern implementations can send and receive request bodies in all request types.
__The requests that should not include body are __ CONNECT __, __ GET __, __ HEAD __, __ OPTIONS __, and __ TRACE __. __
Request Body Types
Request body is parsed by the express body parser, and therefore it can contain any basic JavaScript data types. Notice that this differs from the request parameters and queries.
This also means that you do not know what the data type of any given body parameter will be. It might be necessary to check this in some cases.
TypeScript Body Casting
If you want to enforce type safety, the solution is to validate the user input before using it.
This is usually a good idea even if not using TypeScript, since it is important to know what type all the variables are in your code.
import express, { NextFunction, Request, Response} from 'express'
const server = express()
server.use(express.json())
interface Body {
name: string
age: number
}
const validate = (req: Request, res: Response, next: NextFunction ) => {
const { age, name } = req.body
if (typeof(age) !== 'number' || typeof(name) !== 'string') {
return res.status(400).send('Missing or invalid parameters')
}
next()
}
server.post('/', validate, (req: Request, res: Response) => {
const body: Body = req.body
console.log(body)
res.send(body.name.toUpperCase())
})
server.listen(3000)
Exercise 7: Body Logging
Enable body parsing in your application.
Modify your logger middleware so that in addition to existing functionality, it also logs the request body if it exists.
Solution: https://gitlab.com/bctjs/week3-day2/-/blob/master/examples/day2/countdown.js
Exercise 8: POST Requests
Add two more endpoints to your app:
POST /student should expect the request body to include student id , _name _ and email . If some of these parameters are missing, the endpoint should return a response with status code 400 and an error message. The endpoint should store the student information in an array called students . The endpoint should return an empty response with status code 201.
GET /student/:id should return the information of a single student, identified by the id request parameter. The response should be in JSON format. If there is no such student, the endpoint should return 404.
Modify the GET /students endpoint to return the list of all student ids , without names or emails.
Solution: https://gitlab.com/bctjs/week3-day2/-/blob/master/examples/day2/countdown.js
Exercise 9: PUT and DELETE
Add two more endpoints to your app:
PUT /student/:id should expect the request body to include student name or email . If both are missing, the endpoint should return a response with status code 400 and an error message. The endpoint should update an existing student identified by the request parameter id .
DELETE /student/:id should remove a student identified by the request parameter id .
Both endpoints should return 404 if there is no student matching the request parameter id . On success both endpoint should return an empty response with status code 204.
Solution: https://gitlab.com/bctjs/week3-day2/-/blob/master/examples/day2/countdown.js