10 Express
JavaScript can not only be used on the client-side, but also on the server-side. Node.js is a JavaScript runtime environment that allows to run JavaScript on the server.
Introduction
Even though Node.js allows to create a simple web server, it is not very convenient to use. A simple webserver in Node.js looks like this:
const http = require("http");
const server = http.createServer((request, response) => {
response.writeHead(200, {"Content-Type": "text/plain"});
response.end("Hello World!");
});
server.listen(3000, () => {
console.log("Server running on port 3000");
});
Express is a web framework for Node.js that makes it easier to create web applications. It is fast, unopinionated and minimalist.
Installation
Express can be installed with npm:
npm install express
Example
The following example shows a simple Express application that responds with “Hello World!” to every request:
const express = require("express");
const app = express();
app.get("/", (request, response) => {
response.send("Hello World!");
});
app.listen(3000, () => {
console.log("Server running on port 3000");
});
Routing
Express allows to define routes for different HTTP methods and URLs. There are three main ways to define routes:
Page Controller
Implementing the front and page controller pattern with Express is very simple.
Middleware
Middleware functions are functions that have access to the request object, the response object and the next middleware function. They can be used to execute code before or after a request is handled. They can also be used to modify the request or response objects.
Setup
To use middleware functions, they have to be registered with app.use().
app.use((request, response, next) => {
// before request is handled
next();
// after request is handled
});
NOTE: It depends on the order in which the middleware functions are registered, in which order they are executed. If a function is registered after the route handler, it will not be executed.
Useful Middleware
Middleware can be installed from npm. Some useful middleware functions are:
- body-parser: parses the request body (e.g. to JSON)
- cors: enables CORS
- logger: logs requests
Database
Express does not provide any database integration. However, there are many npm packages that can be used to integrate a database.
MongoDB
MongoDB is a document-oriented database. It stores data in JSON-like documents. MongoDB can be used with Express by using the mongoose package.
Setup
First, the mongoose package has to be installed:
npm install mongoose
Then, the connection to the database has to be established:
// in app.js
const mongoose = require("mongoose");
mongoose.connect("mongodb://localhost:27017/notes");
Model
A model is a class that represents a collection in the database. It can be used to create, read, update and delete documents in the collection.
const mongoose = require("mongoose");
const noteSchema = new mongoose.Schema({
title: {
type: String,
required: true,
minlength: 1,
maxlength: 100
},
content: {
type: String,
required: true,
minlength: 1,
maxlength: 1000
}
});
// make model compatible with the Java Spring REST API
// add id field...
noteSchema.virtual("id").get(function() {
return this._id.toHexString();
});
// ...and use it in the JSON representation
noteSchema.set("toJSON", {
virtuals: true
});
export default mongoose.model("Note", noteSchema);