diff --git a/.vscode/dictionaries/proper-names.txt b/.vscode/dictionaries/proper-names.txt index f8d92998d784fab..f2a24a8eaad167a 100644 --- a/.vscode/dictionaries/proper-names.txt +++ b/.vscode/dictionaries/proper-names.txt @@ -362,7 +362,6 @@ Liskov Lorc Lorde Loycom -Luxon Léonie Macknik Macromedia diff --git a/files/en-us/_redirects.txt b/files/en-us/_redirects.txt index 2e33176f82d43cf..ed2e6420935053d 100644 --- a/files/en-us/_redirects.txt +++ b/files/en-us/_redirects.txt @@ -5648,7 +5648,7 @@ /en-US/docs/Learn/Server-side/Express_Nodejs/Displaying_data/BookInstance_list_page /en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/Displaying_data/BookInstance_list_page /en-US/docs/Learn/Server-side/Express_Nodejs/Displaying_data/Book_detail_page /en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/Displaying_data/Book_detail_page /en-US/docs/Learn/Server-side/Express_Nodejs/Displaying_data/Book_list_page /en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/Displaying_data/Book_list_page -/en-US/docs/Learn/Server-side/Express_Nodejs/Displaying_data/Date_formatting_using_moment /en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/Displaying_data/Date_formatting_using_moment +/en-US/docs/Learn/Server-side/Express_Nodejs/Displaying_data/Date_formatting_using_moment /en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/Displaying_data/BookInstance_list_page /en-US/docs/Learn/Server-side/Express_Nodejs/Displaying_data/Genre_detail_page /en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/Displaying_data/Genre_detail_page /en-US/docs/Learn/Server-side/Express_Nodejs/Displaying_data/Home_page /en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/Displaying_data/Home_page /en-US/docs/Learn/Server-side/Express_Nodejs/Displaying_data/LocalLibrary_base_template /en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/Displaying_data/LocalLibrary_base_template @@ -5886,6 +5886,7 @@ /en-US/docs/Learn_web_development/Extensions/Performance/Resources /en-US/docs/Learn_web_development/Extensions/Performance/Best_practices /en-US/docs/Learn_web_development/Extensions/Performance/Web_Performance_Basics /en-US/docs/Learn_web_development/Extensions/Performance/Best_practices /en-US/docs/Learn_web_development/Extensions/Security_privacy /en-US/docs/Web/Security +/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/Displaying_data/Date_formatting_using_moment /en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/Displaying_data/BookInstance_list_page /en-US/docs/Learn_web_development/Extensions/Transform_animate /en-US/docs/Learn_web_development/Extensions /en-US/docs/Learn_web_development/Getting_started/Basic_setup /en-US/docs/Learn_web_development/Getting_started/Environment_setup/Installing_software /en-US/docs/Learn_web_development/Getting_started/Soft_skills/Job_interviews /en-US/docs/Learn_web_development/Getting_started/Soft_skills/Finding_a_job diff --git a/files/en-us/_wikihistory.json b/files/en-us/_wikihistory.json index acd7d741e1a622f..a5846677bf28c0b 100644 --- a/files/en-us/_wikihistory.json +++ b/files/en-us/_wikihistory.json @@ -9256,16 +9256,6 @@ "david_ross" ] }, - "Learn_web_development/Extensions/Server-side/Express_Nodejs/Displaying_data/Date_formatting_using_moment": { - "modified": "2020-10-15T23:02:33.461Z", - "contributors": [ - "hamishwillee", - "th7nder", - "anorton", - "chrisdavidmills", - "david_ross" - ] - }, "Learn_web_development/Extensions/Server-side/Express_Nodejs/Displaying_data/Genre_detail_page": { "modified": "2020-10-16T01:09:32.792Z", "contributors": [ diff --git a/files/en-us/learn_web_development/extensions/server-side/express_nodejs/deployment/index.md b/files/en-us/learn_web_development/extensions/server-side/express_nodejs/deployment/index.md index dc0190d88a748ea..32fa6b6057e34be 100644 --- a/files/en-us/learn_web_development/extensions/server-side/express_nodejs/deployment/index.md +++ b/files/en-us/learn_web_development/extensions/server-side/express_nodejs/deployment/index.md @@ -107,7 +107,7 @@ In the following subsections, we outline the most important changes that you sho ### Database configuration -So far in this tutorial, we've used a single development database, for which the address and credentials were [hard-coded into **bin/www**](/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/mongoose#connect_to_mongodb). +So far in this tutorial, we've used a single development database, for which the address and credentials were [hard-coded into **server.js**](/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/mongoose#connect_to_mongodb). Since the development database doesn't contain any information that we mind being exposed or corrupted, there is no particular risk in leaking these details. However if you're working with real data, in particular personal user information, then it is very important to protect your database credentials. @@ -116,7 +116,7 @@ For this reason we want to use a different database for production than we use f If your hosting provider supports setting environment variables through a web interface (as many do), one way to do this is to have the server get the database URL from an environment variable. Below we modify the LocalLibrary website to get the database URI from an OS environment variable, if it has been defined, and otherwise use the development database URL. -Open **bin.www** and find the line that sets the MongoDB connection variable. +Open **server.js** and find the line that sets the MongoDB connection variable. It will look something like this: ```js @@ -127,9 +127,9 @@ const mongoDB = Replace the line with the following code that uses `process.env.MONGODB_URI` to get the connection string from an environment variable named `MONGODB_URI` if has been set (use your own database URL instead of the placeholder below). ```js -const dev_db_url = +const devDbUrl = "mongodb+srv://your_user_name:your_password@cluster0.cojoign.mongodb.net/local_library?retryWrites=true&w=majority"; -const mongoDB = process.env.MONGODB_URI || dev_db_url; +const mongoDB = process.env.MONGODB_URI || devDbUrl; ``` > [!NOTE] @@ -150,13 +150,15 @@ Logging calls can have an impact on a high-traffic website. In a production envi One way to minimize "debug" logging in production is to use a module like [debug](https://www.npmjs.com/package/debug) that allows you to control what logging is performed by setting an environment variable. For example, the code fragment below shows how you might set up "author" logging. -The debug variable is declared with the name 'author', and the prefix "author" will be automatically displayed for all logs from this object. +Calling `createDebug("author")` creates a `debug()` function for the "author" _namespace_: every message it logs is prefixed with "author", and it only logs when "author" is listed in the `DEBUG` environment variable. ```js -const debug = require("debug")("author"); +import createDebug from "debug"; + +const debug = createDebug("author"); // Display Author update form on GET. -exports.author_update_get = async (req, res, next) => { +export const authorUpdateGet = async (req, res, next) => { const author = await Author.findById(req.params.id).exec(); if (author === null) { // No results. @@ -196,11 +198,12 @@ Add this to your site using [compression](https://www.npmjs.com/package/compress npm install compression ``` -Open **./app.js** and require the compression library as shown. Add the compression library to the middleware chain with the `use()` method (this should appear before any routes you want compressed — in this case, all of them!) +Open **./app.js** and import the compression library as shown. Add the compression library to the middleware chain with the `use()` method (this should appear before any routes you want compressed — in this case, all of them!) ```js -const catalogRouter = require("./routes/catalog"); // Import routes for "catalog" area of site -const compression = require("compression"); +import compression from "compression"; + +import catalogRouter from "./routes/catalog.js"; // Import routes for "catalog" area of site // Create the Express application object const app = express(); @@ -209,7 +212,7 @@ const app = express(); app.use(compression()); // Compress all routes -app.use(express.static(path.join(__dirname, "public"))); +app.use(express.static(path.join(import.meta.dirname, "public"))); app.use("/", indexRouter); app.use("/users", usersRouter); @@ -231,18 +234,18 @@ Install this at the root of your project by running the following command: npm install helmet ``` -Open **./app.js** and require the _helmet_ library as shown. +Open **./app.js** and import the _helmet_ library as shown. Then add the module to the middleware chain with the `use()` method. ```js -const compression = require("compression"); -const helmet = require("helmet"); +import compression from "compression"; +import helmet from "helmet"; // Create the Express application object const app = express(); // Add helmet to the middleware chain. -// Set CSP headers to allow our Bootstrap and jQuery to be served +// Set CSP headers to allow our Bootstrap scripts to be served app.use( helmet.contentSecurityPolicy({ directives: { @@ -273,13 +276,13 @@ Install this at the root of your project by running the following command: npm install express-rate-limit ``` -Open **./app.js** and require the _express-rate-limit_ library as shown. +Open **./app.js** and import the _express-rate-limit_ library as shown. Then add the module to the middleware chain with the `use()` method. ```js -const compression = require("compression"); -const helmet = require("helmet"); -const RateLimit = require("express-rate-limit"); +import compression from "compression"; +import helmet from "helmet"; +import RateLimit from "express-rate-limit"; const app = express(); @@ -303,27 +306,17 @@ The command above limits all requests to 20 per minute (you can change this as n For node applications, including Express, the **package.json** file contains everything a hosting provider should need to work out the application dependencies and entry point file. -The only important information missing from our current **package.json** is the version of node required by the library. -You can find the version of node that was used for development by entering the command: - -```bash ->node --version -v16.17.1 -``` - -Open **package.json**, and add this information as an **engines > node** as shown (using the version number for your system). +We already specified the minimum Node.js version in **package.json** when we [created the project](/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/development_environment#creating_the_project): ```json { "engines": { - "node": ">=22.0.0" + "node": ">=24.0.0" } } ``` -The hosting service might not support the specific indicated version of node, but this change should ensure that it attempts to use a version with the same major version number, or a more recent version. - -Note that there may be other ways to specify the node version on different hosting services, but the **package.json** approach is widely supported. +Check your hosting provider's instructions to make sure it uses a supported Node.js version that satisfies this requirement. You can check the version installed in an environment with `node --version`. #### Get dependencies and re-test @@ -388,7 +381,7 @@ Now that the repository ("repo") is created on GitHub we are going to want to cl Then copy your application source files into the repo folder, make them part of the repo using _git_, and upload them to GitHub: -1. Copy your Express application into this folder (excluding **/node_modules**, which contains dependency files that you should fetch from npm as needed). +1. Copy your Express application into this folder (excluding **node_modules/**, which contains dependency files that you should fetch from npm as needed). 2. Open a command prompt/terminal and use the `add` command to add all files to git. ```bash diff --git a/files/en-us/learn_web_development/extensions/server-side/express_nodejs/development_environment/express_default_screen.png b/files/en-us/learn_web_development/extensions/server-side/express_nodejs/development_environment/express_default_screen.png deleted file mode 100644 index e86e4005ed06746..000000000000000 Binary files a/files/en-us/learn_web_development/extensions/server-side/express_nodejs/development_environment/express_default_screen.png and /dev/null differ diff --git a/files/en-us/learn_web_development/extensions/server-side/express_nodejs/development_environment/index.md b/files/en-us/learn_web_development/extensions/server-side/express_nodejs/development_environment/index.md index e66ade3bc3423c1..522135dbe2af744 100644 --- a/files/en-us/learn_web_development/extensions/server-side/express_nodejs/development_environment/index.md +++ b/files/en-us/learn_web_development/extensions/server-side/express_nodejs/development_environment/index.md @@ -31,11 +31,11 @@ _Node_ and _Express_ make it very easy to set up your computer in order to start ### What is the Express development environment? -The _Express_ development environment includes an installation of _Node.js_, the _npm package manager_, and (optionally) the _Express Application Generator_ on your local computer. +The _Express_ development environment includes an installation of _Node.js_ and the _npm package manager_ on your local computer. _Node_ and the _npm_ package manager are installed together from prepared binary packages, installers, operating system package managers or from source (as shown in the following sections). _Express_ is then installed by npm as a dependency of your individual _Express_ web applications (along with other libraries like template engines, database drivers, authentication middleware, middleware to serve static files, etc.). -_npm_ can also be used to (globally) install the _Express Application Generator_, a handy tool for creating skeleton _Express_ web apps that follow the [MVC pattern](/en-US/docs/Glossary/MVC). The application generator is optional because you don't _need_ to use this tool to create apps that use Express, or construct Express apps that have the same architectural layout or dependencies. We'll be using it though, because it makes getting started a lot easier, and promotes a modular application structure. +For the Local Library tutorial, we'll build a project that follows the [MVC pattern](/en-US/docs/Glossary/MVC), using a modular application structure that we can extend as needed. > [!NOTE] > Unlike some other web frameworks, the development environment does not include a separate development web server. In _Node_/_Express_ a web application creates and runs its own web server! @@ -81,11 +81,10 @@ After `nvm-windows` has installed, open a command prompt (or PowerShell) and ent nvm install lts ``` -At time of writing the LTS version of nodejs is 22.17.0. -You can set this as the _current version_ to use with the command below: +Run `nvm list` to see the installed versions. For this tutorial, choose Node.js 24 or later. Set it as the _current version_ with the command below, replacing `` with the version you installed: ```bash -nvm use 22.17.0 +nvm use ``` > [!NOTE] @@ -105,12 +104,10 @@ After `nvm` has installed, open a terminal enter the following command to downlo nvm install --lts ``` -At the time of writing, the LTS version of nodejs is 22.17.0. -The command `nvm list` shows the downloaded set of version and the current version. -You can set a particular version as the _current version_ with the command below (the same as for `nvm-windows`) +The command `nvm list` shows the installed versions and the current version. For this tutorial, choose Node.js 24 or later. Set it as the _current version_ with the command below, replacing `` with the version you installed: ```bash -nvm use 22.17.0 +nvm use ``` Use the command `nvm --help` to find out other command-line options. @@ -123,59 +120,17 @@ A good way to do this is to use the "version" command in your terminal/command p ```bash > node -v -v22.17.0 +v24.0.0 ``` The _Node.js_ package manager _npm_ should also have been installed, and can be tested in the same way: ```bash > npm -v -10.9.2 +11.3.0 ``` -As a slightly more exciting test let's create a very basic "pure node" server that prints out "Hello World" in the browser when you visit the correct URL in your browser: - -1. Copy the following text into a file named **hellonode.js**. This uses pure Node features (nothing from Express): - - ```js - // Load HTTP module - const http = require("http"); - - const hostname = "127.0.0.1"; - const port = 3000; - - // Create HTTP server and listen on port 3000 for requests - const server = http.createServer((req, res) => { - // Set the response HTTP header with HTTP status and Content type - res.statusCode = 200; - res.setHeader("Content-Type", "text/plain"); - res.end("Hello World\n"); - }); - - // Listen for request on port 3000, and as a callback function have the port listened on logged - server.listen(port, hostname, () => { - console.log(`Server running at http://${hostname}:${port}/`); - }); - ``` - - The code imports the "http" module and uses it to create a server (`createServer()`) that listens for HTTP requests on port 3000. The script then prints a message to the console about what browser URL you can use to test the server. The `createServer()` function takes as an argument a callback function that will be invoked when an HTTP request is received — this returns a response with an HTTP status code of 200 ("OK") and the plain text "Hello World". - - > [!NOTE] - > Don't worry if you don't understand exactly what this code is doing yet! We'll explain our code in greater detail once we start using Express! - -2. Start the server by navigating into the same directory as your `hellonode.js` file in your command prompt, and calling `node` along with the script name, like so: - - ```bash - node hellonode.js - ``` - - Once the server starts, you will see console output indicating the IP address the server is running on: - - ```plain - Server running at http://127.0.0.1:3000/ - ``` - -3. Navigate to the URL `http://127.0.0.1:3000`. If everything is working, the browser should display the string "Hello World". +The version numbers may differ from those shown above. With both commands working, you can configure the Local Library project. ## Using npm @@ -183,260 +138,207 @@ Next to _Node_ itself, [npm](https://docs.npmjs.com/) is the most important tool `npm` is used to fetch any packages (JavaScript libraries) that an application needs for development, testing, and/or production, and may also be used to run tests and tools used in the development process. > [!NOTE] -> From Node's perspective, _Express_ is just another package that you need to install using npm and then require in your own code. +> From Node's perspective, _Express_ is just another package that you need to install using npm and then import in your own code. You can manually use npm to separately fetch each needed package. Typically we instead manage dependencies using a plain-text definition file named [package.json](https://docs.npmjs.com/files/package.json/). This file lists all the dependencies for a specific JavaScript "package", including the package's name, version, description, initial file to execute, production dependencies, development dependencies, versions of _Node_ it can work with, etc. The **package.json** file should contain everything npm needs to fetch and run your application (if you were writing a reusable library you could use this definition to upload your package to the npm repository and make it available for other users). -### Adding dependencies +### Creating the project -The following steps show how you can use npm to download a package, save it into the project dependencies, and then require it in a Node application. +In this section we'll create the Local Library project. By the end of this article, you'll have its package configuration and dependencies ready. We'll add the application code in [Creating a skeleton website](/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/skeleton_website). -> [!NOTE] -> Here we show the instructions to fetch and install the _Express_ package. Later on we'll show how this package, and others, are already specified for us using the _Express Application Generator_. This section is provided because it is useful to understand how npm works and what is being created by the application generator. - -1. First create a directory for your new application and navigate into it: +1. Create a directory for the application and navigate into it: ```bash - mkdir myapp - cd myapp + mkdir express-locallibrary-tutorial + cd express-locallibrary-tutorial ``` -2. Use the npm `init` command to create a **package.json** file for your application. This command prompts you for a number of things, including the name and version of your application and the name of the initial entry point file (by default this is **index.js**). For now, just accept the defaults: +2. Use the npm `init` command to create a **package.json** file configured for ES modules: ```bash - npm init + npm init --yes --init-type=module ``` - If you display the **package.json** file (`cat package.json`), you will see the defaults that you accepted, ending with the license. + The [`--init-type=module`](https://docs.npmjs.com/cli/commands/npm-init/#init-type) option sets `"type": "module"` instead of the default `"type": "commonjs"`. + +3. Open **package.json** in your text editor. npm creates a file like the following, using the directory name as the package name: ```json { - "name": "myapp", + "name": "express-locallibrary-tutorial", "version": "1.0.0", + "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, + "keywords": [], "author": "", "license": "ISC", - "description": "" + "type": "module" } ``` -3. Now install Express in the `myapp` directory and save it in the dependencies list of your **package.json** file: - - ```bash - npm install express - ``` - - The dependencies section of your **package.json** will now appear at the end of the **package.json** file and will include _Express_. +4. Add `"private": true` and an `engines` field at the top level of **package.json**, alongside `name` and `version`: ```json { - "name": "myapp", - "version": "1.0.0", - "description": "", - "main": "index.js", - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" - }, - "author": "", - "license": "ISC", - "dependencies": { - "express": "^5.1.0" + "private": true, + "engines": { + "node": ">=24.0.0" } } ``` -4. To use the Express library you call the `require()` function in your **index.js** file to include it in your application. - Create this file now, in the root of the "myapp" application directory, and give it the following contents: + Setting `private` to `true` prevents accidental publication to the npm registry. The `engines` field declares the minimum supported Node.js version. Keep the generated fields for now; we'll replace `scripts` below. - ```js - const express = require("express"); +5. Delete the following fields, which are only useful if you are publishing to the npm registry: `description`, `main`, `keywords`, `author`, `license`. - const app = express(); - const port = 3000; - - app.get("/", (req, res) => { - res.send("Hello World!"); - }); - - app.listen(port, () => { - console.log(`Example app listening on port ${port}!`); - }); - ``` - - This code shows a minimal "HelloWorld" Express web application. - This imports the "express" module using `require()` and uses it to create a server (`app`) that listens for HTTP requests on port 3000 and prints a message to the console explaining what browser URL you can use to test the server. - The `app.get()` function only responds to HTTP `GET` requests with the specified URL path ('/'), in this case by calling a function to send our _Hello World!_ message. - - > [!NOTE] - > The backticks in the `` `Example app listening on port ${port}!` `` let us interpolate the value of `$port` into the string. +### Adding dependencies -5. You can start the server by calling node with the script in your command prompt: +Install the packages that the project needs, from inside the **express-locallibrary-tutorial** directory: - ```bash - node index.js - ``` +```bash +npm install debug express http-errors morgan pug +``` - You will see the following console output: +These packages each have a role in the application: - ```plain - Example app listening on port 3000 - ``` +- `debug` displays diagnostic messages when enabled through the `DEBUG` environment variable. +- `express` provides the web framework. +- `http-errors` creates HTTP errors, such as a 404 for an unknown route. +- `morgan` logs HTTP requests. +- `pug` renders HTML from templates. -6. Navigate to the URL `http://localhost:3000/`. - If everything is working, the browser should display the string "Hello World!". +The [`npm install`](https://docs.npmjs.com/cli/commands/npm-install/) command downloads these packages and their dependencies into **node_modules**, adds them to `dependencies` in **package.json**, and creates **package-lock.json** to record the resolved versions. Keep both package files in version control so other developers can install the project's dependencies. When a lockfile is already available, `npm ci` installs its recorded versions. -### Development dependencies +> [!NOTE] +> It is a good idea to regularly update to the latest compatible versions of your dependency libraries — this may even be done automatically or semi-automatically as part of a {{glossary("continuous integration")}} setup. +> +> Usually library updates to the minor and patch version remain compatible. +> When you install a package, npm records its version in **package.json** with a `^` prefix (for example, `"express": "^5.2.1"`). +> This allows you to update to the latest compatible `minor.patch` version by running: +> +> ```bash +> npm update --save +> ``` +> +> Major versions change the compatibility. +> For those updates we'll need to manually update the `package.json` and code that uses the library, and extensively re-test the project. -If a dependency is only used during development, you should instead save it as a "development dependency" (so that your package users don't have to install it in production). For example, to use the popular JavaScript Linting tool [ESLint](https://eslint.org/) you would call npm as shown: +We'll install additional packages, such as the database driver, when we need them later in the tutorial. For a broader introduction to development tools and their configuration, see [Introducing a complete toolchain](/en-US/docs/Learn_web_development/Extensions/Client-side_tools/Introducing_complete_toolchain). -```bash -npm install eslint --save-dev -``` +### Running tasks -The following entry would then be added to your application's **package.json**: +In addition to defining dependencies, you can define named scripts in **package.json** and use npm to execute them. Replace the generated `scripts` object, including its placeholder `test` command, with these commands: ```json { - "devDependencies": { - "eslint": "^9.30.1" + "scripts": { + "start": "node server.js", + "devstart": "node --watch server.js" } } ``` -> [!NOTE] -> "[Linters]()" are tools that perform static analysis on software in order to recognize and report adherence/non-adherence to some set of coding best practice. +The `start` script runs the application's entry point, **server.js**. The `devstart` script uses Node's watch mode to restart the server when an imported JavaScript file changes. We'll try both commands with a minimal server below. -### Running tasks - -In addition to defining and fetching dependencies you can also define _named_ scripts in your **package.json** files and call npm to execute them with the [run-script](https://docs.npmjs.com/cli/commands/npm-run/) command. This approach is commonly used to automate running tests and parts of the development or build toolchain (e.g., running tools to minify JavaScript, shrink images, LINT/analyze your code, etc.). - -> [!NOTE] -> Task runners like [Gulp](https://gulpjs.com/) and [Grunt](https://gruntjs.com/) can also be used to run tests and other external tools. - -For example, to define a script to run the _eslint_ development dependency that we specified in the previous section we might add the following script block to our **package.json** file (assuming that our application source is in a folder `/src/js`): +Your **package.json** should now look like this. The dependency version numbers may be newer, depending on when you install the packages. ```json { + "name": "express-locallibrary-tutorial", + "version": "1.0.0", "scripts": { - // … - "lint": "eslint src/js" - // … + "start": "node server.js", + "devstart": "node --watch server.js" + }, + "type": "module", + "private": true, + "engines": { + "node": ">=24.0.0" + }, + "dependencies": { + "debug": "^4.4.3", + "express": "^5.2.1", + "http-errors": "^2.0.1", + "morgan": "^1.12.0", + "pug": "^3.0.4" } } ``` -To explain a little further, `eslint src/js` is a command that we could enter in our terminal/command line to run `eslint` on JavaScript files contained in the `src/js` directory inside our app directory. Including the above inside our app's package.json file provides a shortcut for this command — `lint`. +### Trying a minimal server -We would then be able to run _eslint_ using npm by calling: +To check that your environment and npm scripts work, create a file named **server.js** alongside **package.json** with the following contents: -```bash -npm run-script lint -# OR (using the alias) -npm run lint -``` +```js +import express from "express"; -This example may not look any shorter than the original command, but you can include much bigger commands inside your npm scripts, including chains of multiple commands. You could identify a single npm script that runs all your tests at once. +const app = express(); +const port = 3000; -## Installing the Express Application Generator +app.get("/", (req, res) => { + res.send("Hello World!"); +}); -The [Express Application Generator](https://expressjs.com/en/starter/generator/) tool generates an Express application "skeleton". Install the generator using npm as shown: - -```bash -npm install express-generator -g +app.listen(port, () => { + console.log(`Server running at http://localhost:${port}/`); +}); ``` -> [!NOTE] -> You may need to prefix this line with `sudo` on Ubuntu or macOS. The `-g` flag installs the tool globally so that you can call it from anywhere. - -To create an _Express_ app named "helloworld" with the default settings, navigate to where you want to create it and run the app as shown: - -```bash -express helloworld -``` - -> [!NOTE] -> Unless you're using an old nodejs version (< 8.2.0), you could alternatively skip the installation and run express-generator with [npx](https://github.com/npm/npx#readme). -> This has the same effect as installing and then running `express-generator` but does not install the package on your system: -> -> ```bash -> npx express-generator helloworld -> ``` - -You can also specify the template library to use and a number of other settings. -Use the `help` command to see all the options: +This imports Express and creates an application. The `app.get()` method responds to requests for `/` with the text "Hello World!", and `app.listen()` starts the server on port 3000. Node treats **server.js** as an ES module because we set `"type": "module"` in **package.json**. -```bash -express --help -``` +1. In your project directory, start the server using the npm script: -The generator will create the new Express app in a sub folder of your current location, displaying build progress on the console. -On completion, the tool will display the commands you need to enter to install the Node dependencies and start the app. + ```bash + npm start + ``` -The new app will have a **package.json** file in its root directory. -You can open this to see what dependencies are installed, including Express and the template library Jade: + You should see the following message in the terminal: -```json -{ - "name": "helloworld", - "version": "0.0.0", - "private": true, - "scripts": { - "start": "node ./bin/www" - }, - "dependencies": { - "cookie-parser": "~1.4.4", - "debug": "~2.6.9", - "express": "~4.16.1", - "http-errors": "~1.6.3", - "jade": "~1.11.0", - "morgan": "~1.9.1" - } -} -``` + ```plain + Server running at http://localhost:3000/ + ``` -Install all the dependencies for the helloworld app using npm as shown: +2. Open `http://localhost:3000/` in your browser. You should see "Hello World!". +3. Stop the server with **Ctrl+C**, then start it in watch mode: -```bash -cd helloworld -npm install -``` + ```bash + npm run devstart + ``` -Then run the app (the commands are slightly different for Windows and Linux/macOS), as shown below: +4. Change the message in `res.send()` to "Hello again!" and save **server.js**. Node restarts the server automatically. Reload the page to see the updated message. +5. Stop the server with **Ctrl+C** and delete this temporary **server.js** file. We'll add the project's server and application files in the skeleton website chapter. Keep the npm scripts; they will run that server too. -```bash -# Run helloworld on Windows with Command Prompt -SET DEBUG=helloworld:* & npm start +### Ignoring generated and local files -# Run helloworld on Windows with PowerShell -SET DEBUG=helloworld:* | npm start +Create a file named **.gitignore** alongside **package.json** with the following contents: -# Run helloworld on Linux/macOS -DEBUG=helloworld:* npm start +```plain +node_modules/ +*.log +.env ``` -The DEBUG command creates useful logging, resulting in an output like the following: - -```bash ->SET DEBUG=helloworld:* & npm start +This keeps installed dependencies, log files, and local environment settings out of version control. The dependencies can be installed again from the package files. -> helloworld@0.0.0 start D:\GitHub\express-tests\helloworld -> node ./bin/www +Your project directory should now contain: - helloworld:server Listening on port 3000 +0ms +```plain +express-locallibrary-tutorial +├── .gitignore +├── node_modules +│ └── [A lot of installed dependency files] +├── package-lock.json +└── package.json ``` -Open a browser and navigate to `http://localhost:3000/` to see the default Express welcome page. - -![Express - Generated App Default Screen](express_default_screen.png) - -We'll talk more about the generated app when we get to the article on generating a skeleton application. +This is a good starting point for our tutorial. We'll add actual application files like JavaScript files, templates, and stylesheet when we get to the [Skeleton website](/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/skeleton_website) chapter. ## Summary -You now have a Node development environment up and running on your computer that can be used for creating Express web applications. You've also seen how npm can be used to import Express into an application, and also how you can create applications using the Express Application Generator tool and then run them. +You now have a Node development environment and the Local Library project's package configuration, dependencies, and npm scripts. You've checked the setup with a minimal Express server, and the project is ready for the application files we'll add in the tutorial. In the next article we start working through a tutorial to build a complete web application using this environment and associated tools. @@ -444,7 +346,6 @@ In the next article we start working through a tutorial to build a complete web - [Downloads](https://nodejs.org/en/download) page (nodejs.org) - [Installing Express](https://expressjs.com/en/starter/installing/) (expressjs.com) -- [Express Application Generator](https://expressjs.com/en/starter/generator/) (expressjs.com) - [Using Node.js with Windows subsystem for Linux](https://learn.microsoft.com/en-us/windows/dev-environment/javascript/) (docs.microsoft.com) {{PreviousMenuNext("Learn_web_development/Extensions/Server-side/Express_Nodejs/Introduction", "Learn_web_development/Extensions/Server-side/Express_Nodejs/Tutorial_local_library_website", "Learn_web_development/Extensions/Server-side/Express_Nodejs")}} diff --git a/files/en-us/learn_web_development/extensions/server-side/express_nodejs/displaying_data/author_detail_page/index.md b/files/en-us/learn_web_development/extensions/server-side/express_nodejs/displaying_data/author_detail_page/index.md index de23ae58eac6677..a616552fd48fc8a 100644 --- a/files/en-us/learn_web_development/extensions/server-side/express_nodejs/displaying_data/author_detail_page/index.md +++ b/files/en-us/learn_web_development/extensions/server-side/express_nodejs/displaying_data/author_detail_page/index.md @@ -5,23 +5,25 @@ page-type: learn-module-chapter sidebar: learnsidebar --- +{{PreviousMenuNext("Learn_web_development/Extensions/Server-side/Express_Nodejs/Displaying_data/Book_detail_page", "Learn_web_development/Extensions/Server-side/Express_Nodejs/Displaying_data/BookInstance_detail_page_and_challenge", "Learn_web_development/Extensions/Server-side/Express_Nodejs/Displaying_data")}} + The author detail page needs to display the information about the specified `Author`, identified using their (automatically generated) `_id` field value, along with a list of all the `Book` objects associated with that `Author`. ## Controller -Open **/controllers/authorController.js**. +Open **controllers/authorController.js**. -Add the following lines to the top of the file to `require()` the `Book` module needed by the author detail page. +Add the following lines to the top of the file to import the `Book` module needed by the author detail page. ```js -const Book = require("../models/book"); +import Book from "../models/book.js"; ``` -Find the exported `author_detail()` controller method and replace it with the following code. +Find the exported `authorDetail()` controller method and replace it with the following code. ```js // Display detail page for a specific Author. -exports.author_detail = async (req, res, next) => { +export const authorDetail = async (req, res, next) => { // Get details of author and all their books (in parallel) const [author, allBooksByAuthor] = await Promise.all([ Author.findById(req.params.id).exec(), @@ -50,7 +52,7 @@ If the author is found then the retrieved database information is rendered using ## View -Create **/views/author_detail.pug** and copy in the following text. +Create **views/author_detail.pug** and paste in the following text. ```pug extends layout @@ -84,7 +86,4 @@ Run the application and open your browser to `http://localhost:3000/`. Select th > [!NOTE] > The appearance of the author _lifespan_ dates is ugly! We'll address that in the final challenge in this article. -## Next steps - -- Return to [Express Tutorial Part 5: Displaying library data](/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/Displaying_data). -- Proceed to final subarticle of part 5 : [BookInstance detail page and challenge](/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/Displaying_data/BookInstance_detail_page_and_challenge). +{{PreviousMenuNext("Learn_web_development/Extensions/Server-side/Express_Nodejs/Displaying_data/Book_detail_page", "Learn_web_development/Extensions/Server-side/Express_Nodejs/Displaying_data/BookInstance_detail_page_and_challenge", "Learn_web_development/Extensions/Server-side/Express_Nodejs/Displaying_data")}} diff --git a/files/en-us/learn_web_development/extensions/server-side/express_nodejs/displaying_data/author_list_page/index.md b/files/en-us/learn_web_development/extensions/server-side/express_nodejs/displaying_data/author_list_page/index.md index eeda88500df4351..f339137eec0bba3 100644 --- a/files/en-us/learn_web_development/extensions/server-side/express_nodejs/displaying_data/author_list_page/index.md +++ b/files/en-us/learn_web_development/extensions/server-side/express_nodejs/displaying_data/author_list_page/index.md @@ -5,17 +5,19 @@ page-type: learn-module-chapter sidebar: learnsidebar --- +{{PreviousMenuNext("Learn_web_development/Extensions/Server-side/Express_Nodejs/Displaying_data/BookInstance_list_page", "Learn_web_development/Extensions/Server-side/Express_Nodejs/Displaying_data/Genre_detail_page", "Learn_web_development/Extensions/Server-side/Express_Nodejs/Displaying_data")}} + The author list page needs to display a list of all authors in the database, with each author name linked to its associated author detail page. The date of birth and date of death should be listed after the name on the same line. ## Controller The author list controller function needs to get a list of all `Author` instances, and then pass these to the template for rendering. -Open **/controllers/authorController.js**. Find the exported `author_list()` controller method near the top of the file and replace it with the following code. +Open **controllers/authorController.js**. Find the exported `authorList()` controller method near the top of the file and replace it with the following code. ```js // Display list of all Authors. -exports.author_list = async (req, res, next) => { +export const authorList = async (req, res, next) => { const allAuthors = await Author.find().sort({ family_name: 1 }).exec(); res.render("author_list", { title: "Author List", @@ -32,7 +34,7 @@ Once the promise is fulfilled the route handler renders the **author_list**(.pug ## View -Create **/views/author_list.pug** and replace its content with the text below. +Create **views/author_list.pug** and replace its content with the text below. ```pug extends layout @@ -55,11 +57,13 @@ Run the application and open your browser to `http://localhost:3000/`. Then sele ![Author List Page - Express Local Library site](locallibary_express_author_list.png) > [!NOTE] -> The appearance of the author _lifespan_ dates is ugly! You can improve this using the [same approach](/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/Displaying_data/Date_formatting_using_moment) as we used for the `BookInstance` list (adding the virtual property for the lifespan to the `Author` model). +> The appearance of the author _lifespan_ dates is ugly! You can improve this using the [same approach](/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/Displaying_data/BookInstance_list_page#formatting_the_dates) as we used for the `BookInstance` list (adding the virtual property for the lifespan to the `Author` model). > > However, as the author may not be dead or may have missing birth/death data, in this case we need to ignore missing dates or references to nonexistent properties. One way to deal with this is to return either a formatted date, or a blank string, depending on whether the property is defined. For example: > -> `return this.date_of_birth ? DateTime.fromJSDate(this.date_of_birth).toLocaleString(DateTime.DATE_MED) : '';` +> ```js +> return this.date_of_birth ? dateFormatter.format(this.date_of_birth) : ""; +> ``` ## Genre list page—challenge! @@ -69,16 +73,10 @@ In this section you should implement your own genre list page. The page should d The genre list controller function needs to get a list of all `Genre` instances, and then pass these to the template for rendering. -1. You will need to edit `genre_list()` in **/controllers/genreController.js**. -2. The implementation is almost exactly the same as the `author_list()` controller. - - Sort the results by name, in ascending order. - +1. You will need to edit `genreList()` in **controllers/genreController.js**. +2. The implementation is almost exactly the same as the `authorList()` controller. Sort the results by name, in ascending order. 3. The template to be rendered should be named **genre_list.pug**. 4. The template to be rendered should be passed the variables `title` ('Genre List') and `genre_list` (the list of genres returned from `Genre.find()`). 5. The view should match the screenshot/requirements above (this should have a very similar structure/format to the Author list view, except for the fact that genres do not have dates). -## Next steps - -Return to [Express Tutorial Part 5: Displaying library data](/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/Displaying_data). - -Proceed to the next subarticle of part 5: [Genre detail page](/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/Displaying_data/Genre_detail_page). +{{PreviousMenuNext("Learn_web_development/Extensions/Server-side/Express_Nodejs/Displaying_data/BookInstance_list_page", "Learn_web_development/Extensions/Server-side/Express_Nodejs/Displaying_data/Genre_detail_page", "Learn_web_development/Extensions/Server-side/Express_Nodejs/Displaying_data")}} diff --git a/files/en-us/learn_web_development/extensions/server-side/express_nodejs/displaying_data/book_detail_page/index.md b/files/en-us/learn_web_development/extensions/server-side/express_nodejs/displaying_data/book_detail_page/index.md index 67008dba5ebbc9e..f615edc829efcfd 100644 --- a/files/en-us/learn_web_development/extensions/server-side/express_nodejs/displaying_data/book_detail_page/index.md +++ b/files/en-us/learn_web_development/extensions/server-side/express_nodejs/displaying_data/book_detail_page/index.md @@ -5,15 +5,17 @@ page-type: learn-module-chapter sidebar: learnsidebar --- +{{PreviousMenuNext("Learn_web_development/Extensions/Server-side/Express_Nodejs/Displaying_data/Genre_detail_page", "Learn_web_development/Extensions/Server-side/Express_Nodejs/Displaying_data/Author_detail_page", "Learn_web_development/Extensions/Server-side/Express_Nodejs/Displaying_data")}} + The _Book detail page_ needs to display the information for a specific `Book` (identified using its automatically generated `_id` field value), along with information about each associated copy in the library (`BookInstance`). Wherever we display an author, genre, or book instance, these should be linked to the associated detail page for that item. ## Controller -Open **/controllers/bookController.js**. Find the exported `book_detail()` controller method and replace it with the following code. +Open **controllers/bookController.js**. Find the exported `bookDetail()` controller method and replace it with the following code. ```js // Display detail page for a specific book. -exports.book_detail = async (req, res, next) => { +export const bookDetail = async (req, res, next) => { // Get details of books, book instances for specific book const [book, bookInstances] = await Promise.all([ Book.findById(req.params.id).populate("author").populate("genre").exec(), @@ -36,7 +38,7 @@ exports.book_detail = async (req, res, next) => { ``` > [!NOTE] -> We don't need to require any additional modules in this step, as we already imported the dependencies when we implemented the home page controller. +> We don't need to import any additional modules in this step, as we already imported the dependencies when we implemented the home page controller. The approach is exactly the same as described for the [Genre detail page](/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/Displaying_data/Genre_detail_page). The route controller function uses `Promise.all()` to query the specified `Book` and its associated copies (`BookInstance`) in parallel. @@ -46,7 +48,7 @@ Since the key 'title' is used to give name to the webpage (as defined in the hea ## View -Create **/views/book_detail.pug** and add the text below. +Create **views/book_detail.pug** and add the text below. ```pug extends layout @@ -108,7 +110,4 @@ Run the application and open your browser to `http://localhost:3000/`. Select th ![Book Detail Page - Express Local Library site](locallibary_express_book_detail.png) -## Next steps - -- Return to [Express Tutorial Part 5: Displaying library data](/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/Displaying_data). -- Proceed to the next subarticle of part 5: [Author detail page](/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/Displaying_data/Author_detail_page). +{{PreviousMenuNext("Learn_web_development/Extensions/Server-side/Express_Nodejs/Displaying_data/Genre_detail_page", "Learn_web_development/Extensions/Server-side/Express_Nodejs/Displaying_data/Author_detail_page", "Learn_web_development/Extensions/Server-side/Express_Nodejs/Displaying_data")}} diff --git a/files/en-us/learn_web_development/extensions/server-side/express_nodejs/displaying_data/book_list_page/index.md b/files/en-us/learn_web_development/extensions/server-side/express_nodejs/displaying_data/book_list_page/index.md index e333786ab3a5213..55907e66cf1eb49 100644 --- a/files/en-us/learn_web_development/extensions/server-side/express_nodejs/displaying_data/book_list_page/index.md +++ b/files/en-us/learn_web_development/extensions/server-side/express_nodejs/displaying_data/book_list_page/index.md @@ -5,17 +5,19 @@ page-type: learn-module-chapter sidebar: learnsidebar --- +{{PreviousMenuNext("Learn_web_development/Extensions/Server-side/Express_Nodejs/Displaying_data/Home_page", "Learn_web_development/Extensions/Server-side/Express_Nodejs/Displaying_data/BookInstance_list_page", "Learn_web_development/Extensions/Server-side/Express_Nodejs/Displaying_data")}} + Next we'll implement our book list page. This page needs to display a list of all books in the database along with their author, with each book title being a hyperlink to its associated book detail page. ## Controller The book list controller function needs to get a list of all `Book` objects in the database, sort them, and then pass these to the template for rendering. -Open **/controllers/bookController.js**. Find the exported `book_list()` controller method and replace it with the following code. +Open **controllers/bookController.js**. Find the exported `bookList()` controller method and replace it with the following code. ```js // Display list of all books. -exports.book_list = async (req, res, next) => { +export const bookList = async (req, res, next) => { const allBooks = await Book.find({}, "title author") .sort({ title: 1 }) .populate("author") @@ -36,7 +38,7 @@ The final part of the route handler calls `render()`, specifying the **book_list ## View -Create **/views/book_list.pug** and copy in the text below. +Create **views/book_list.pug** and paste in the text below. ```pug extends layout @@ -68,7 +70,4 @@ Run the application (see [Testing the routes](/en-US/docs/Learn_web_development/ ![Book List Page - Express Local Library site](new_book_list.png) -## Next steps - -- Return to [Express Tutorial Part 5: Displaying library data](/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/Displaying_data). -- Proceed to the next subarticle of part 5: [BookInstance list page](/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/Displaying_data/BookInstance_list_page). +{{PreviousMenuNext("Learn_web_development/Extensions/Server-side/Express_Nodejs/Displaying_data/Home_page", "Learn_web_development/Extensions/Server-side/Express_Nodejs/Displaying_data/BookInstance_list_page", "Learn_web_development/Extensions/Server-side/Express_Nodejs/Displaying_data")}} diff --git a/files/en-us/learn_web_development/extensions/server-side/express_nodejs/displaying_data/bookinstance_detail_page_and_challenge/index.md b/files/en-us/learn_web_development/extensions/server-side/express_nodejs/displaying_data/bookinstance_detail_page_and_challenge/index.md index dda41e91c3160e7..e51753f21f4ea1f 100644 --- a/files/en-us/learn_web_development/extensions/server-side/express_nodejs/displaying_data/bookinstance_detail_page_and_challenge/index.md +++ b/files/en-us/learn_web_development/extensions/server-side/express_nodejs/displaying_data/bookinstance_detail_page_and_challenge/index.md @@ -5,18 +5,20 @@ page-type: learn-module-chapter sidebar: learnsidebar --- +{{PreviousMenu("Learn_web_development/Extensions/Server-side/Express_Nodejs/Displaying_data/Author_detail_page", "Learn_web_development/Extensions/Server-side/Express_Nodejs/Displaying_data")}} + ## BookInstance detail page The `BookInstance` detail page needs to display the information for each `BookInstance`, identified using its (automatically generated) `_id` field value. This will include the `Book` name (as a link to the _Book detail page_) along with other information in the record. ### Controller -Open **/controllers/bookinstanceController.js**. -Find the exported `bookinstance_detail()` controller method and replace it with the following code. +Open **controllers/bookinstanceController.js**. +Find the exported `bookInstanceDetail()` controller method and replace it with the following code. ```js // Display detail page for a specific BookInstance. -exports.bookinstance_detail = async (req, res, next) => { +export const bookInstanceDetail = async (req, res, next) => { const bookInstance = await BookInstance.findById(req.params.id) .populate("book") .exec(); @@ -43,7 +45,7 @@ Otherwise the returned data is rendered using the **bookinstance_detail.pug** vi ### View -Create **/views/bookinstance_detail.pug** and copy in the content below. +Create **views/bookinstance_detail.pug** and paste in the content below. ```pug extends layout @@ -78,10 +80,10 @@ Run the application and open your browser to `http://localhost:3000/`. Select th ## Challenge -Currently most _dates_ displayed on the site use the default JavaScript format (e.g., _Tue Oct 06 2020 15:49:58 GMT+1100 (AUS Eastern Daylight Time))_. The challenge for this article is to improve the appearance of the date display for `Author` lifespan information (date of death/birth) and for _BookInstance detail_ pages to use the format: Oct 6th, 2016. +Currently most _dates_ displayed on the site use the default JavaScript format (e.g., _Tue Oct 06 2020 15:49:58 GMT+1100 (AUS Eastern Daylight Time))_. The challenge for this article is to improve the appearance of the date display for `Author` lifespan information (date of death/birth) and for _BookInstance detail_ pages to use the format: Oct 6, 2016. > [!NOTE] -> You can use the same approach as we used for the _Book Instance List_ (adding the virtual property for the lifespan to the `Author` model and use [luxon](https://www.npmjs.com/package/luxon) to format the date strings). +> You can use the same approach as we used for the _Book Instance List_ (adding the virtual property for the lifespan to the `Author` model and use {{jsxref("Intl")}} to format the date strings). To complete this challenge, you must: @@ -89,6 +91,4 @@ To complete this challenge, you must: 2. Update the `Author` model to add a lifespan virtual property. The lifespan should look like: _date_of_birth - date_of_death_, where both values have the same date format as `BookInstance.due_back_formatted`. 3. Use `Author.lifespan` in all views where you currently explicitly use `date_of_birth` and `date_of_death`. -## Next steps - -- Return to [Express Tutorial Part 5: Displaying library data](/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/Displaying_data#displaying_library_data_tutorial_subarticles). +{{PreviousMenu("Learn_web_development/Extensions/Server-side/Express_Nodejs/Displaying_data/Author_detail_page", "Learn_web_development/Extensions/Server-side/Express_Nodejs/Displaying_data")}} diff --git a/files/en-us/learn_web_development/extensions/server-side/express_nodejs/displaying_data/bookinstance_list_page/index.md b/files/en-us/learn_web_development/extensions/server-side/express_nodejs/displaying_data/bookinstance_list_page/index.md index 2a61f1218a2e7da..26b1a75b230d096 100644 --- a/files/en-us/learn_web_development/extensions/server-side/express_nodejs/displaying_data/bookinstance_list_page/index.md +++ b/files/en-us/learn_web_development/extensions/server-side/express_nodejs/displaying_data/bookinstance_list_page/index.md @@ -5,18 +5,20 @@ page-type: learn-module-chapter sidebar: learnsidebar --- +{{PreviousMenuNext("Learn_web_development/Extensions/Server-side/Express_Nodejs/Displaying_data/Book_list_page", "Learn_web_development/Extensions/Server-side/Express_Nodejs/Displaying_data/Author_list_page", "Learn_web_development/Extensions/Server-side/Express_Nodejs/Displaying_data")}} + Next we'll implement our list of all book copies (`BookInstance`) in the library. This page needs to include the title of the `Book` associated with each `BookInstance` (linked to its detail page) along with other information in the `BookInstance` model, including the status, imprint, and unique id of each copy. The unique id text should be linked to the `BookInstance` detail page. ## Controller The `BookInstance` list controller function needs to get a list of all book instances, populate the associated book information, and then pass the list to the template for rendering. -Open `/controllers/bookinstanceController.js`. -Find the exported `bookinstance_list()` controller method and replace it with the following code. +Open **controllers/bookinstanceController.js**. +Find the exported `bookInstanceList()` controller method and replace it with the following code. ```js // Display list of all BookInstances. -exports.bookinstance_list = async (req, res, next) => { +export const bookInstanceList = async (req, res, next) => { const allBookInstances = await BookInstance.find().populate("book").exec(); res.render("bookinstance_list", { @@ -36,7 +38,7 @@ The last part of the code calls `render()`, specifying the **bookinstance_list** ## View -Create **/views/bookinstance_list.pug** and copy in the text below. +Create **views/bookinstance_list.pug** and paste in the text below. ```pug extends layout @@ -56,7 +58,7 @@ block content else span.text-warning #{val.status} if val.status!='Available' - span (Due: #{val.due_back} ) + span (Due: #{val.due_back}) else p There are no book copies in this library. @@ -64,13 +66,48 @@ block content This view is much the same as all the others. It extends the layout, replacing the _content_ block, displays the `title` passed in from the controller, and iterates through all the book copies in `bookinstance_list`. For each copy we display its status (color coded) and if the book is not available, its expected return date. One new feature is introduced—we can use dot notation after a tag to assign a class. So `span.text-success` will be compiled to `` (and might also be written in Pug as `span(class="text-success")`). +## Formatting the dates + +The default rendering of dates from our models is very ugly: _Mon Apr 10 2020 15:49:58 GMT+1100 (AUS Eastern Daylight Time)_. In this section we'll show how you can update the _BookInstance List_ page from the previous section to present the `due_back` field in a more friendly format: _Apr 10, 2020_. + +The approach we will use is to create a virtual property in our `BookInstance` model that returns the formatted date. We'll do the actual formatting using {{jsxref("Intl")}}. + +> [!NOTE] +> It is possible to format the strings directly in our Pug templates, or we could format the string in a number of other places. Using a virtual property allows us to get the formatted date in exactly the same way as we get `due_back` currently. + +Open **models/bookinstance.js**. +Add the virtual property `due_back_formatted` just after the URL property. + +```js +const dateFormatter = new Intl.DateTimeFormat("en-US", { + year: "numeric", + month: "short", + day: "numeric", + timeZone: "UTC", +}); + +BookInstanceSchema.virtual("due_back_formatted").get(function () { + return dateFormatter.format(this.due_back); +}); +``` + +Dates entered as `YYYY-MM-DD` (as our forms will do later) are stored as midnight UTC, so we set the `timeZone` option to `"UTC"`. +Otherwise those dates would be shown in the server's local time zone and appear one day early on servers west of UTC. + +Open **views/bookinstance_list.pug** and replace `due_back` with `due_back_formatted`. + +```pug + if val.status != 'Available' + //span (Due: #{val.due_back}) + span (Due: #{val.due_back_formatted}) +``` + +That's it. If you go to _All book-instances_ in the sidebar, you should now see all the due dates are far more attractive! + ## What does it look like? Run the application, open your browser to `http://localhost:3000/`, then select the _All book-instances_ link. If everything is set up correctly, your site should look something like the following screenshot. ![BookInstance List Page - Express Local Library site](locallibary_express_bookinstance_list.png) -## Next steps - -- Return to [Express Tutorial Part 5: Displaying library data](/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/Displaying_data). -- Proceed to the next subarticle of part 5: [Date formatting using luxon](/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/Displaying_data/Date_formatting_using_moment). +{{PreviousMenuNext("Learn_web_development/Extensions/Server-side/Express_Nodejs/Displaying_data/Book_list_page", "Learn_web_development/Extensions/Server-side/Express_Nodejs/Displaying_data/Author_list_page", "Learn_web_development/Extensions/Server-side/Express_Nodejs/Displaying_data")}} diff --git a/files/en-us/learn_web_development/extensions/server-side/express_nodejs/displaying_data/bookinstance_list_page/locallibary_express_bookinstance_list.png b/files/en-us/learn_web_development/extensions/server-side/express_nodejs/displaying_data/bookinstance_list_page/locallibary_express_bookinstance_list.png index d8ae5bddf258687..de81ecec5ef85bc 100644 Binary files a/files/en-us/learn_web_development/extensions/server-side/express_nodejs/displaying_data/bookinstance_list_page/locallibary_express_bookinstance_list.png and b/files/en-us/learn_web_development/extensions/server-side/express_nodejs/displaying_data/bookinstance_list_page/locallibary_express_bookinstance_list.png differ diff --git a/files/en-us/learn_web_development/extensions/server-side/express_nodejs/displaying_data/date_formatting_using_moment/index.md b/files/en-us/learn_web_development/extensions/server-side/express_nodejs/displaying_data/date_formatting_using_moment/index.md deleted file mode 100644 index e9616f4eb916de6..000000000000000 --- a/files/en-us/learn_web_development/extensions/server-side/express_nodejs/displaying_data/date_formatting_using_moment/index.md +++ /dev/null @@ -1,59 +0,0 @@ ---- -title: Date formatting using luxon -slug: Learn_web_development/Extensions/Server-side/Express_Nodejs/Displaying_data/Date_formatting_using_moment -page-type: learn-module-chapter -sidebar: learnsidebar ---- - -The default rendering of dates from our models is very ugly: _Mon Apr 10 2020 15:49:58 GMT+1100 (AUS Eastern Daylight Time)_. In this section we'll show how you can update the _BookInstance List_ page from the previous section to present the `due_date` field in a more friendly format: Apr 10th, 2023. - -The approach we will use is to create a virtual property in our `BookInstance` model that returns the formatted date. We'll do the actual formatting using [luxon](https://www.npmjs.com/package/luxon), a powerful, modern, and friendly library for parsing, validating, manipulating, formatting and localizing dates. - -> [!NOTE] -> It is possible to use _luxon_ to format the strings directly in our Pug templates, or we could format the string in a number of other places. Using a virtual property allows us to get the formatted date in exactly the same way as we get the `due_date` currently. - -## Install luxon - -Enter the following command in the root of the project: - -```bash -npm install luxon -``` - -## Create the virtual property - -1. Open **./models/bookinstance.js**. -2. At the top of the page, import _luxon_. - - ```js - const { DateTime } = require("luxon"); - ``` - -Add the virtual property `due_back_formatted` just after the URL property. - -```js -BookInstanceSchema.virtual("due_back_formatted").get(function () { - return DateTime.fromJSDate(this.due_back).toLocaleString(DateTime.DATE_MED); -}); -``` - -> [!NOTE] -> Luxon can import strings in many formats and export to both predefined and free-form formats. In this case we use `fromJSDate()` to import a JavaScript date string and `toLocaleString()` to output the date in `DATE_MED` format in English: Apr 10th, 2023. -> For information about other formats and date string internationalization see the Luxon documentation on [formatting](https://github.com/moment/luxon/blob/master/docs/formatting.md#formatting). - -## Update the view - -Open **/views/bookinstance_list.pug** and replace `due_back` with `due_back_formatted`. - -```pug - if val.status != 'Available' - //span (Due: #{val.due_back} ) - span (Due: #{val.due_back_formatted} ) -``` - -That's it. If you go to _All book-instances_ in the sidebar, you should now see all the due dates are far more attractive! - -## Next steps - -- Return to [Express Tutorial Part 5: Displaying library data](/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/Displaying_data). -- Proceed to the next subarticle of part 5: [Author list page and Genre list page challenge](/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/Displaying_data/Author_list_page). diff --git a/files/en-us/learn_web_development/extensions/server-side/express_nodejs/displaying_data/genre_detail_page/index.md b/files/en-us/learn_web_development/extensions/server-side/express_nodejs/displaying_data/genre_detail_page/index.md index 8069c5b437bccb6..50b979a901007ca 100644 --- a/files/en-us/learn_web_development/extensions/server-side/express_nodejs/displaying_data/genre_detail_page/index.md +++ b/files/en-us/learn_web_development/extensions/server-side/express_nodejs/displaying_data/genre_detail_page/index.md @@ -5,6 +5,8 @@ page-type: learn-module-chapter sidebar: learnsidebar --- +{{PreviousMenuNext("Learn_web_development/Extensions/Server-side/Express_Nodejs/Displaying_data/Author_list_page", "Learn_web_development/Extensions/Server-side/Express_Nodejs/Displaying_data/Book_detail_page", "Learn_web_development/Extensions/Server-side/Express_Nodejs/Displaying_data")}} + The genre _detail_ page needs to display the information for a particular genre instance, using its automatically generated `_id` field value as the identifier. The ID of the required genre record is encoded at the end of the URL and extracted automatically based on the route definition (**/genre/:id**). It is then accessed within the controller via the request parameters: `req.params.id`. @@ -13,17 +15,17 @@ The page should display the genre name and a list of all books in the genre with ## Controller -Open **/controllers/genreController.js** and require the `Book` module at the top of the file (the file should already `require()` the `Genre` module). +Open **controllers/genreController.js** and import the `Book` module at the top of the file (the file should already import the `Genre` module). ```js -const Book = require("../models/book"); +import Book from "../models/book.js"; ``` -Find the exported `genre_detail()` controller method and replace it with the following code. +Find the exported `genreDetail()` controller method and replace it with the following code. ```js // Display detail page for a specific Genre. -exports.genre_detail = async (req, res, next) => { +export const genreDetail = async (req, res, next) => { // Get details of genre and all associated books (in parallel) const [genre, booksInGenre] = await Promise.all([ Genre.findById(req.params.id).exec(), @@ -52,7 +54,7 @@ If the genre does not exist in the database (i.e., it may have been deleted) the In this case we want to display a "not found" page, so we create an `Error` object and pass it to the `next` middleware function in the chain. > [!NOTE] -> Errors passed to the `next` middleware function propagate through to our error handling code (this was set up when we [generated the app skeleton](/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/skeleton_website#app.js). For more information, see [Handling Errors](/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/Introduction#handling_errors) and [Handling errors and exceptions in the route functions](/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/routes#handling_errors_and_exceptions_in_the_route_functions)). +> Errors passed to the `next` middleware function propagate through to our error handling code (this was set up when we [created the app skeleton](/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/skeleton_website#app.js). For more information, see [Handling Errors](/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/Introduction#handling_errors) and [Handling errors and exceptions in the route functions](/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/routes#handling_errors_and_exceptions_in_the_route_functions)). If the `genre` is found, then we call `render()` to display the view. The view template is **genre_detail** (.pug). @@ -60,7 +62,7 @@ The values for the title, `genre` and `booksInGenre` are passed into the templat ## View -Create **/views/genre_detail.pug** and fill it with the text below: +Create **views/genre_detail.pug** and fill it with the text below: ```pug extends layout @@ -100,7 +102,4 @@ Run the application and open your browser to `http://localhost:3000/`. Select th > The most likely cause is that the ID being passed into the mongoose methods is not actually an ID. > [`Mongoose.prototype.isValidObjectId()`]() can be used to check whether a particular ID is valid. -## Next steps - -- Return to [Express Tutorial Part 5: Displaying library data](/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/Displaying_data). -- Proceed to the next subarticle of part 5: [Book detail page](/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/Displaying_data/Book_detail_page). +{{PreviousMenuNext("Learn_web_development/Extensions/Server-side/Express_Nodejs/Displaying_data/Author_list_page", "Learn_web_development/Extensions/Server-side/Express_Nodejs/Displaying_data/Book_detail_page", "Learn_web_development/Extensions/Server-side/Express_Nodejs/Displaying_data")}} diff --git a/files/en-us/learn_web_development/extensions/server-side/express_nodejs/displaying_data/home_page/index.md b/files/en-us/learn_web_development/extensions/server-side/express_nodejs/displaying_data/home_page/index.md index 6d38a0e56bdf726..92e6aad350ea143 100644 --- a/files/en-us/learn_web_development/extensions/server-side/express_nodejs/displaying_data/home_page/index.md +++ b/files/en-us/learn_web_development/extensions/server-side/express_nodejs/displaying_data/home_page/index.md @@ -5,6 +5,8 @@ page-type: learn-module-chapter sidebar: learnsidebar --- +{{PreviousMenuNext("Learn_web_development/Extensions/Server-side/Express_Nodejs/Displaying_data/LocalLibrary_base_template", "Learn_web_development/Extensions/Server-side/Express_Nodejs/Displaying_data/Book_list_page", "Learn_web_development/Extensions/Server-side/Express_Nodejs/Displaying_data")}} + The first page we'll create will be the website home page, which is accessible from either the site (`/`) or catalog (`catalog/`) root. This will display some static text describing the site, along with dynamically calculated "counts" of different record types in the database. We've already created a route for the home page. In order to complete the page we need to update our controller function to fetch "counts" of records from the database, and create a view (template) that we can use to render the page. @@ -16,17 +18,17 @@ We've already created a route for the home page. In order to complete the page w ## Route We created our index page routes in a [previous tutorial](/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/routes). -As a reminder, all the route functions are defined in **/routes/catalog.js**: +As a reminder, all the route functions are defined in **routes/catalog.js**: ```js // GET catalog home page. -router.get("/", book_controller.index); // This actually maps to /catalog/ because we import the route with a /catalog prefix +router.get("/", bookController.index); // This actually maps to /catalog/ because we import the route with a /catalog prefix ``` -The book controller index function passed as a parameter (`book_controller.index`) has a "placeholder" implementation defined in **/controllers/bookController.js**: +The book controller index function passed as a parameter (`bookController.index`) has a "placeholder" implementation defined in **controllers/bookController.js**: ```js -exports.index = async (req, res, next) => { +export const index = async (req, res, next) => { res.send("NOT IMPLEMENTED: Site Home Page"); }; ``` @@ -37,27 +39,27 @@ It is this controller function that we extend to get information from our models The index controller function needs to fetch information about how many `Book`, `BookInstance` (all), `BookInstance` (available), `Author`, and `Genre` records we have in the database, render this data in a template to create an HTML page, and then return it in an HTTP response. -Open **/controllers/bookController.js**. Near the top of the file you should see the exported `index()` function. +Open **controllers/bookController.js**. Near the top of the file you should see the exported `index()` function. ```js -const Book = require("../models/book"); +import Book from "../models/book.js"; -exports.index = async (req, res, next) => { +export const index = async (req, res, next) => { res.send("NOT IMPLEMENTED: Site Home Page"); }; ``` Replace all the code above with the following code fragment. -The first thing this does is import (`require()`) all the models. +The first thing this does is import all the models. We need to do this because we'll be using them to get our counts of documents. ```js -const Book = require("../models/book"); -const Author = require("../models/author"); -const Genre = require("../models/genre"); -const BookInstance = require("../models/bookinstance"); +import Book from "../models/book.js"; +import Author from "../models/author.js"; +import Genre from "../models/genre.js"; +import BookInstance from "../models/bookinstance.js"; -exports.index = async (req, res, next) => { +export const index = async (req, res, next) => { // Get details of books, book instances, authors and genre counts (in parallel) const [ numBooks, @@ -92,7 +94,7 @@ Because the queries for document counts are independent of each other we use [`P The method returns a new promise that we [`await`](/en-US/docs/Web/JavaScript/Reference/Operators/await) for completion (execution pauses within _this function_ at `await`). When all the queries complete, the promise returned by `all()` fulfills, continuing execution of the route handler function, and populating the array with the results of the database queries. -We then call [`res.render()`](https://expressjs.com/en/5x/api/#res.render), specifying a view (template) named '**index**' and objects mapping the results of the database queries to the view template. +We then call [`res.render()`](https://expressjs.com/en/5x/api/response/#resrender), specifying a view (template) named '**index**' and objects mapping the results of the database queries to the view template. The data is supplied as key-value pairs, and can be accessed in the template using the key. > [!NOTE] @@ -104,7 +106,7 @@ If any of the database operations fail, the exception that is thrown will cause ## View -Open **/views/index.pug** and replace its content with the text below. +Open **views/index.pug** and replace its content with the text below. ```pug extends layout @@ -142,7 +144,4 @@ At this point we should have created everything needed to display the index page > [!NOTE] > You won't be able to _use_ the sidebar links yet because the URLs, views, and templates for those pages haven't been defined. If you try you'll get errors like "NOT IMPLEMENTED: Book list" for example, depending on the link you click on. These string literals (which will be replaced with proper data) were specified in the different controllers that live inside your "controllers" file. -## Next steps - -- Return to [Express Tutorial Part 5: Displaying library data](/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/Displaying_data). -- Proceed to the next subarticle of part 5: [Book list page](/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/Displaying_data/Book_list_page). +{{PreviousMenuNext("Learn_web_development/Extensions/Server-side/Express_Nodejs/Displaying_data/LocalLibrary_base_template", "Learn_web_development/Extensions/Server-side/Express_Nodejs/Displaying_data/Book_list_page", "Learn_web_development/Extensions/Server-side/Express_Nodejs/Displaying_data")}} diff --git a/files/en-us/learn_web_development/extensions/server-side/express_nodejs/displaying_data/index.md b/files/en-us/learn_web_development/extensions/server-side/express_nodejs/displaying_data/index.md index 1818393ccd43c90..b8c101418376add 100644 --- a/files/en-us/learn_web_development/extensions/server-side/express_nodejs/displaying_data/index.md +++ b/files/en-us/learn_web_development/extensions/server-side/express_nodejs/displaying_data/index.md @@ -47,16 +47,15 @@ You need to read and work through each one of these in turn, before moving on to 3. [Home page](/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/Displaying_data/Home_page) 4. [Book list page](/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/Displaying_data/Book_list_page) 5. [BookInstance list page](/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/Displaying_data/BookInstance_list_page) -6. [Date formatting using luxon](/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/Displaying_data/Date_formatting_using_moment) -7. [Author list page and Genre list page challenge](/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/Displaying_data/Author_list_page) -8. [Genre detail page](/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/Displaying_data/Genre_detail_page) -9. [Book detail page](/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/Displaying_data/Book_detail_page) -10. [Author detail page](/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/Displaying_data/Author_detail_page) -11. [BookInstance detail page and challenge](/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/Displaying_data/BookInstance_detail_page_and_challenge) +6. [Author list page and Genre list page challenge](/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/Displaying_data/Author_list_page) +7. [Genre detail page](/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/Displaying_data/Genre_detail_page) +8. [Book detail page](/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/Displaying_data/Book_detail_page) +9. [Author detail page](/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/Displaying_data/Author_detail_page) +10. [BookInstance detail page and challenge](/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/Displaying_data/BookInstance_detail_page_and_challenge) ## Summary -We've now created all the "read-only" pages for our site: a home page that displays counts of instances of each of our models, and list and detail pages for our books, book instances, authors, and genres. Along the way, we've gained a lot of fundamental knowledge about controllers, managing flow control when using asynchronous operations, creating views using _Pug_, querying the site's database using models, passing information to a view, and creating and extending templates. The challenges will also have taught readers a little about date handling using _Luxon_. +We've now created all the "read-only" pages for our site: a home page that displays counts of instances of each of our models, and list and detail pages for our books, book instances, authors, and genres. Along the way, we've gained a lot of fundamental knowledge about controllers, managing flow control when using asynchronous operations, creating views using _Pug_, querying the site's database using models, passing information to a view, and creating and extending templates. In our next article, we'll build on our knowledge, creating HTML forms and form handling code to start modifying the data stored by the site. @@ -64,6 +63,5 @@ In our next article, we'll build on our knowledge, creating HTML forms and form - [Using Template engines with Express](https://expressjs.com/en/guide/using-template-engines/) (Express docs) - [Pug](https://pugjs.org/api/getting-started.html) (Pug docs) -- [Luxon](https://moment.github.io/luxon/#/) (Luxon docs) {{PreviousMenuNext("Learn_web_development/Extensions/Server-side/Express_Nodejs/routes", "Learn_web_development/Extensions/Server-side/Express_Nodejs/forms", "Learn_web_development/Extensions/Server-side/Express_Nodejs")}} diff --git a/files/en-us/learn_web_development/extensions/server-side/express_nodejs/displaying_data/locallibrary_base_template/index.md b/files/en-us/learn_web_development/extensions/server-side/express_nodejs/displaying_data/locallibrary_base_template/index.md index 6553a3e59d7a2ad..515f2545bc5f93f 100644 --- a/files/en-us/learn_web_development/extensions/server-side/express_nodejs/displaying_data/locallibrary_base_template/index.md +++ b/files/en-us/learn_web_development/extensions/server-side/express_nodejs/displaying_data/locallibrary_base_template/index.md @@ -5,9 +5,11 @@ page-type: learn-module-chapter sidebar: learnsidebar --- +{{PreviousMenuNext("Learn_web_development/Extensions/Server-side/Express_Nodejs/Displaying_data/Template_primer", "Learn_web_development/Extensions/Server-side/Express_Nodejs/Displaying_data/Home_page", "Learn_web_development/Extensions/Server-side/Express_Nodejs/Displaying_data")}} + Now that we understand how to extend templates using Pug, let's start by creating a base template for the project. This will have a sidebar with links for the pages we hope to create across the tutorial articles (e.g., to display and create books, genres, authors, etc.) and a main content area that we'll override in each of our individual pages. -Open **/views/layout.pug** and replace the content with the code below. +Open **views/layout.pug** and replace the content with the code below. ```pug doctype html @@ -15,7 +17,7 @@ html(lang='en') head title= title meta(charset='utf-8') - meta(name='viewport', content='width=device-width') + meta(name='viewport', content='width=device-width, initial-scale=1') link(rel="stylesheet", href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.7/dist/css/bootstrap.min.css", integrity="sha384-LN+7fdVzj6u52u30Kp6M/trliBMCMKTyK833zpbD+pXdCLuTusPj697FH4R/5mcr", crossorigin="anonymous") script(src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.7/dist/js/bootstrap.bundle.min.js", integrity="sha384-ndDqU0Gzau9qJ1lfW4pNLlhNTkCfHzAVBReH9diLvGRem5+R9g2FzA8ZGN954O5Q", crossorigin="anonymous") link(rel='stylesheet', href='/stylesheets/style.css') @@ -58,7 +60,7 @@ The template uses (and includes) JavaScript and CSS from [Bootstrap](https://get The layout should be fairly obvious if you've read our above [Template primer](/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/Displaying_data/Template_primer). Note the use of `block content` as a placeholder for where the content for our individual pages will be placed. -The base template also references a local CSS file (**style.css**) that provides a little additional styling. Open **/public/stylesheets/style.css** and replace its content with the following CSS code: +The base template also references a local CSS file (**style.css**) that provides a little additional styling. Open **public/stylesheets/style.css** (which has been an empty file) and add the following: ```css .sidebar-nav { @@ -70,7 +72,4 @@ The base template also references a local CSS file (**style.css**) that provides Now we have a base template for creating pages with a sidebar. In the next sections we will use it to define the individual pages. -## Next steps - -- Return to [Express Tutorial Part 5: Displaying library data](/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/Displaying_data). -- Proceed to the next subarticle of part 5: [Home page](/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/Displaying_data/Home_page). +{{PreviousMenuNext("Learn_web_development/Extensions/Server-side/Express_Nodejs/Displaying_data/Template_primer", "Learn_web_development/Extensions/Server-side/Express_Nodejs/Displaying_data/Home_page", "Learn_web_development/Extensions/Server-side/Express_Nodejs/Displaying_data")}} diff --git a/files/en-us/learn_web_development/extensions/server-side/express_nodejs/displaying_data/template_primer/index.md b/files/en-us/learn_web_development/extensions/server-side/express_nodejs/displaying_data/template_primer/index.md index 36027d7deea7b2a..9943746e48bfbb9 100644 --- a/files/en-us/learn_web_development/extensions/server-side/express_nodejs/displaying_data/template_primer/index.md +++ b/files/en-us/learn_web_development/extensions/server-side/express_nodejs/displaying_data/template_primer/index.md @@ -5,6 +5,8 @@ page-type: learn-module-chapter sidebar: learnsidebar --- +{{NextMenu("Learn_web_development/Extensions/Server-side/Express_Nodejs/Displaying_data/LocalLibrary_base_template", "Learn_web_development/Extensions/Server-side/Express_Nodejs/Displaying_data")}} + A template is a text file defining the _structure_ or layout of an output file, with placeholders used to represent where data will be inserted when the template is rendered (in _Express_, templates are referred to as _views_). ## Express template choices @@ -18,11 +20,11 @@ Different template languages use different approaches for defining layout and ma ## Template configuration -The _LocalLibrary_ was configured to use [Pug](https://pugjs.org/api/getting-started.html) when we [created the skeleton website](/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/skeleton_website). You should see the pug module included as a dependency in the website's **package.json** file, and the following configuration settings in the **app.js** file. The settings tell us that we're using pug as the view engine, and that _Express_ should search for templates in the **/views** subdirectory. +The _LocalLibrary_ was configured to use [Pug](https://pugjs.org/api/getting-started.html) when we [created the skeleton website](/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/skeleton_website). You should see the pug module included as a dependency in the website's **package.json** file, and the following configuration settings in the **app.js** file. The settings tell us that we're using pug as the view engine, and that _Express_ should search for templates in the **views/** subdirectory. ```js // View engine setup -app.set("views", path.join(__dirname, "views")); +app.set("views", path.join(import.meta.dirname, "views")); app.set("view engine", "pug"); ``` @@ -30,11 +32,12 @@ If you look in the views directory you will see the .pug files for the project's These include the view for the home page (**index.pug**) and base template (**layout.pug**) that we will need to replace with our own content. ```plain -/express-locallibrary-tutorial # the project root - /views - error.pug - index.pug - layout.pug +express-locallibrary-tutorial +├── views +│ ├── error.pug +│ ├── index.pug +│ └── layout.pug +... ``` ## Template syntax @@ -165,7 +168,4 @@ block content p Welcome to #{title} ``` -## Next steps - -- Return to [Express Tutorial Part 5: Displaying library data](/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/Displaying_data). -- Proceed to the next subarticle of part 5: [The LocalLibrary base template](/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/Displaying_data/LocalLibrary_base_template). +{{NextMenu("Learn_web_development/Extensions/Server-side/Express_Nodejs/Displaying_data/LocalLibrary_base_template", "Learn_web_development/Extensions/Server-side/Express_Nodejs/Displaying_data")}} diff --git a/files/en-us/learn_web_development/extensions/server-side/express_nodejs/forms/create_author_form/index.md b/files/en-us/learn_web_development/extensions/server-side/express_nodejs/forms/create_author_form/index.md index 36f0fe2a6b0b160..3832cc91dc43534 100644 --- a/files/en-us/learn_web_development/extensions/server-side/express_nodejs/forms/create_author_form/index.md +++ b/files/en-us/learn_web_development/extensions/server-side/express_nodejs/forms/create_author_form/index.md @@ -5,36 +5,38 @@ page-type: learn-module-chapter sidebar: learnsidebar --- +{{PreviousMenuNext("Learn_web_development/Extensions/Server-side/Express_Nodejs/forms/Create_genre_form", "Learn_web_development/Extensions/Server-side/Express_Nodejs/forms/Create_book_form", "Learn_web_development/Extensions/Server-side/Express_Nodejs/forms")}} + This subarticle shows how to define a page for creating `Author` objects. ## Import validation and sanitization methods -As with the [genre form](/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/forms/Create_genre_form), to use _express-validator_ we have to _require_ the functions we want to use. +As with the [genre form](/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/forms/Create_genre_form), to use _express-validator_ we have to _import_ the functions we want to use. -Open **/controllers/authorController.js**, and add the following line at the top of the file (above the route functions): +Open **controllers/authorController.js**, and add the following line at the top of the file (above the route functions): ```js -const { body, validationResult } = require("express-validator"); +import { body, validationResult } from "express-validator"; ``` ## Controller—get route -Find the exported `author_create_get()` controller method and replace it with the following code. This renders the **author_form.pug** view, passing a `title` variable. +Find the exported `authorCreateGet()` controller method and replace it with the following code. This renders the **author_form.pug** view, passing a `title` variable. ```js // Display Author create form on GET. -exports.author_create_get = (req, res, next) => { +export const authorCreateGet = (req, res, next) => { res.render("author_form", { title: "Create Author" }); }; ``` ## Controller—post route -Find the exported `author_create_post()` controller method, and replace it with the following code. +Find the exported `authorCreatePost()` controller method, and replace it with the following code. ```js // Handle Author create on POST. -exports.author_create_post = [ +export const authorCreatePost = [ // Validate and sanitize fields. body("first_name") .trim() @@ -133,7 +135,7 @@ The validation code demonstrates several new features: ## View -Create **/views/author_form.pug** and copy in the text below. +Create **views/author_form.pug** and paste in the text below. ```pug extends layout @@ -173,10 +175,4 @@ Run the application, open your browser to `http://localhost:3000/`, then select ![Author Create Page - Express Local Library site](locallibary_express_author_create_empty.png) -> [!NOTE] -> If you experiment with various input formats for the dates, you may find that the format `yyyy-mm-dd` misbehaves. This is because JavaScript treats date strings as including the time of 0 hours, but additionally treats date strings in that format (the ISO 8601 standard) as including the time 0 hours UTC, rather than the local time. If your time zone is west of UTC, the date display, being local, will be one day before the date you entered. This is one of several complexities (such as multi-word family names and multi-author books) that we are not addressing here. - -## Next steps - -- Return to [Express Tutorial Part 6: Working with forms](/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/forms). -- Proceed to the next subarticle of part 6: [Create Book form](/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/forms/Create_book_form). +{{PreviousMenuNext("Learn_web_development/Extensions/Server-side/Express_Nodejs/forms/Create_genre_form", "Learn_web_development/Extensions/Server-side/Express_Nodejs/forms/Create_book_form", "Learn_web_development/Extensions/Server-side/Express_Nodejs/forms")}} diff --git a/files/en-us/learn_web_development/extensions/server-side/express_nodejs/forms/create_book_form/index.md b/files/en-us/learn_web_development/extensions/server-side/express_nodejs/forms/create_book_form/index.md index 2efbe9242c0b88e..011f7b067295d4d 100644 --- a/files/en-us/learn_web_development/extensions/server-side/express_nodejs/forms/create_book_form/index.md +++ b/files/en-us/learn_web_development/extensions/server-side/express_nodejs/forms/create_book_form/index.md @@ -5,23 +5,25 @@ page-type: learn-module-chapter sidebar: learnsidebar --- +{{PreviousMenuNext("Learn_web_development/Extensions/Server-side/Express_Nodejs/forms/Create_author_form", "Learn_web_development/Extensions/Server-side/Express_Nodejs/forms/Create_BookInstance_form", "Learn_web_development/Extensions/Server-side/Express_Nodejs/forms")}} + This subarticle shows how to define a page/form to create `Book` objects. This is a little more complicated than the equivalent `Author` or `Genre` pages because we need to get and display available `Author` and `Genre` records in our `Book` form. ## Import validation and sanitization methods -Open **/controllers/bookController.js**, and add the following line at the top of the file (before the route functions): +Open **controllers/bookController.js**, and add the following line at the top of the file (before the route functions): ```js -const { body, validationResult } = require("express-validator"); +import { body, validationResult } from "express-validator"; ``` ## Controller—get route -Find the exported `book_create_get()` controller method and replace it with the following code: +Find the exported `bookCreateGet()` controller method and replace it with the following code: ```js // Display book create form on GET. -exports.book_create_get = async (req, res, next) => { +export const bookCreateGet = async (req, res, next) => { // Get all authors and genres, which we can use for adding to our book. const [allAuthors, allGenres] = await Promise.all([ Author.find().sort({ family_name: 1 }).exec(), @@ -41,11 +43,11 @@ These are then passed to the view **`book_form.pug`** as variables named `author ## Controller—post route -Find the exported `book_create_post()` controller method and replace it with the following code. +Find the exported `bookCreatePost()` controller method and replace it with the following code. ```js // Handle book create on POST. -exports.book_create_post = [ +export const bookCreatePost = [ // Convert the genre to an array. (req, res, next) => { if (!Array.isArray(req.body.genre)) { @@ -161,7 +163,7 @@ for (const genre of allGenres) { ## View -Create **/views/book_form.pug** and copy in the text below. +Create **views/book_form.pug** and paste in the text below. ```pug extends layout @@ -226,8 +228,4 @@ Run the application, open your browser to `http://localhost:3000/`, then select ![Screenshot of empty Local library Create Book form on localhost:3000. The page is divided into two columns. The narrow left column has a vertical navigation bar with 10 links separated into two sections by a light-colored horizontal line. The top section link to already created data. The bottom links go to create new data forms. The wide right column has the create book form with a 'Create Book' heading and four input fields labeled 'Title', 'Author', 'Summary', 'ISBN' and 'Genre' followed by four genre checkboxes: fantasy, science fiction, french poetry and action. There is a 'Submit' button at the bottom of the form.](locallibary_express_book_create_empty.png) -## Next steps - -Return to [Express Tutorial Part 6: Working with forms](/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/forms). - -Proceed to the next subarticle of part 6: [Create BookInstance form](/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/forms/Create_BookInstance_form). +{{PreviousMenuNext("Learn_web_development/Extensions/Server-side/Express_Nodejs/forms/Create_author_form", "Learn_web_development/Extensions/Server-side/Express_Nodejs/forms/Create_BookInstance_form", "Learn_web_development/Extensions/Server-side/Express_Nodejs/forms")}} diff --git a/files/en-us/learn_web_development/extensions/server-side/express_nodejs/forms/create_bookinstance_form/index.md b/files/en-us/learn_web_development/extensions/server-side/express_nodejs/forms/create_bookinstance_form/index.md index 4633a753d198e9d..6c35fc89df85451 100644 --- a/files/en-us/learn_web_development/extensions/server-side/express_nodejs/forms/create_bookinstance_form/index.md +++ b/files/en-us/learn_web_development/extensions/server-side/express_nodejs/forms/create_bookinstance_form/index.md @@ -5,30 +5,32 @@ page-type: learn-module-chapter sidebar: learnsidebar --- +{{PreviousMenuNext("Learn_web_development/Extensions/Server-side/Express_Nodejs/forms/Create_book_form", "Learn_web_development/Extensions/Server-side/Express_Nodejs/forms/Delete_author_form", "Learn_web_development/Extensions/Server-side/Express_Nodejs/forms")}} + This subarticle shows how to define a page/form to create `BookInstance` objects. This is very much like the form we used to [create `Book` objects](/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/forms/Create_book_form). ## Import validation and sanitization methods -Open **/controllers/bookinstanceController.js**, and add the following lines at the top of the file: +Open **controllers/bookinstanceController.js**, and add the following lines at the top of the file: ```js -const { body, validationResult } = require("express-validator"); +import { body, validationResult } from "express-validator"; ``` ## Controller—get route -At the top of the file, require the _Book_ module (needed because each `BookInstance` is associated with a particular `Book`). +At the top of the file, import the _Book_ module (needed because each `BookInstance` is associated with a particular `Book`). ```js -const Book = require("../models/book"); +import Book from "../models/book.js"; ``` -Find the exported `bookinstance_create_get()` controller method and replace it with the following code. +Find the exported `bookInstanceCreateGet()` controller method and replace it with the following code. ```js // Display BookInstance create form on GET. -exports.bookinstance_create_get = async (req, res, next) => { +export const bookInstanceCreateGet = async (req, res, next) => { const allBooks = await Book.find({}, "title").sort({ title: 1 }).exec(); res.render("bookinstance_form", { @@ -44,11 +46,11 @@ Because of this, `selected_book` will have a value of `undefined` in the templat ## Controller—post route -Find the exported `bookinstance_create_post()` controller method and replace it with the following code. +Find the exported `bookInstanceCreatePost()` controller method and replace it with the following code. ```js // Handle BookInstance create on POST. -exports.bookinstance_create_post = [ +export const bookInstanceCreatePost = [ // Validate and sanitize fields. body("book", "Book must be specified").trim().isLength({ min: 1 }).escape(), body("imprint", "Imprint must be specified") @@ -102,7 +104,7 @@ If the data is valid, we save the new `BookInstance` record and redirect the use ## View -Create **/views/bookinstance_form.pug** and copy in the text below. +Create **views/bookinstance_form.pug** and paste in the text below. ```pug extends layout @@ -167,7 +169,7 @@ Add the `due_back_yyyy_mm_dd()` virtual function shown below (after the `due_bac ```js BookInstanceSchema.virtual("due_back_yyyy_mm_dd").get(function () { - return DateTime.fromJSDate(this.due_back).toISODate(); // format 'YYYY-MM-DD' + return this.due_back ? this.due_back.toISOString().slice(0, 10) : ""; }); ``` @@ -178,7 +180,4 @@ Then select the _Create new book instance (copy)_ link. If everything is set up ![Create BookInstance of the Local library application screenshot from localhost:3000. The page is divided into two columns. The narrow left column has a vertical navigation bar with 10 links separated into two sections by a light-colored horizontal line. The top section link to already created data. The bottom links go to create new data forms. The wide right column has the create book instance form with a 'Create BookInstance' heading and four input fields labeled 'Book', 'Imprint', 'Date when book available' and 'Status'. The form is filled. There is a 'Submit' button at the bottom of the form.](locallibary_express_bookinstance_create_empty.png) -## Next steps - -- Return to [Express Tutorial Part 6: Working with forms](/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/forms). -- Proceed to the next subarticle of part 6: [Delete Author form](/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/forms/Delete_author_form). +{{PreviousMenuNext("Learn_web_development/Extensions/Server-side/Express_Nodejs/forms/Create_book_form", "Learn_web_development/Extensions/Server-side/Express_Nodejs/forms/Delete_author_form", "Learn_web_development/Extensions/Server-side/Express_Nodejs/forms")}} diff --git a/files/en-us/learn_web_development/extensions/server-side/express_nodejs/forms/create_genre_form/index.md b/files/en-us/learn_web_development/extensions/server-side/express_nodejs/forms/create_genre_form/index.md index 5b82b7dabb29b5a..22741b9697d8261 100644 --- a/files/en-us/learn_web_development/extensions/server-side/express_nodejs/forms/create_genre_form/index.md +++ b/files/en-us/learn_web_development/extensions/server-side/express_nodejs/forms/create_genre_form/index.md @@ -1,43 +1,45 @@ --- -title: Create genre form +title: Create Genre form slug: Learn_web_development/Extensions/Server-side/Express_Nodejs/forms/Create_genre_form page-type: learn-module-chapter sidebar: learnsidebar --- +{{NextMenu("Learn_web_development/Extensions/Server-side/Express_Nodejs/forms/Create_author_form", "Learn_web_development/Extensions/Server-side/Express_Nodejs/forms")}} + This sub article shows how we define our page to create `Genre` objects (this is a good place to start because the `Genre` has only one field, its `name`, and no dependencies). Like any other pages, we need to set up routes, controllers, and views. ## Import validation and sanitization methods -To use the _express-validator_ in our controllers we have to _require_ the functions we want to use from the `'express-validator'` module. +To use the _express-validator_ in our controllers we have to _import_ the functions we want to use from the `'express-validator'` module. -Open **/controllers/genreController.js**, and add the following line at the top of the file, before any route handler functions: +Open **controllers/genreController.js**, and add the following line at the top of the file, before any route handler functions: ```js -const { body, validationResult } = require("express-validator"); +import { body, validationResult } from "express-validator"; ``` -Note that `require("express-validator")` is just a function call that returns an object, and we [destructure](/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring) the two properties, `body` and `validationResult`, from the object, so we can use them as variables directly. +This declaration imports the two named exports, `body` and `validationResult`, so we can use them directly. ## Controller—get route -Find the exported `genre_create_get()` controller method and replace it with the following code. +Find the exported `genreCreateGet()` controller method and replace it with the following code. This renders the **genre_form.pug** view, passing a title variable. ```js // Display Genre create form on GET. -exports.genre_create_get = (req, res, next) => { +export const genreCreateGet = (req, res, next) => { res.render("genre_form", { title: "Create Genre" }); }; ``` ## Controller—post route -Find the exported `genre_create_post()` controller method and replace it with the following code. +Find the exported `genreCreatePost()` controller method and replace it with the following code. ```js // Handle Genre create on POST. -exports.genre_create_post = [ +export const genreCreatePost = [ // Validate and sanitize the name field. body("name", "Genre name must contain at least 3 characters") .trim() @@ -165,7 +167,7 @@ res.render("genre_form", { }); ``` -Create **/views/genre_form.pug** and copy in the text below. +Create **views/genre_form.pug** and paste in the text below. ```pug extends layout @@ -214,7 +216,4 @@ The only error we validate against server-side is that the genre field must have > input#name.form-control(type='text', placeholder='Fantasy, Poetry etc.' name='name' required value=(undefined===genre ? '' : genre.name) ) > ``` -## Next steps - -1. Return to [Express Tutorial Part 6: Working with forms.](/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/forms) -2. Proceed to the next sub article of part 6: [Create Author form](/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/forms/Create_author_form). +{{NextMenu("Learn_web_development/Extensions/Server-side/Express_Nodejs/forms/Create_author_form", "Learn_web_development/Extensions/Server-side/Express_Nodejs/forms")}} diff --git a/files/en-us/learn_web_development/extensions/server-side/express_nodejs/forms/delete_author_form/index.md b/files/en-us/learn_web_development/extensions/server-side/express_nodejs/forms/delete_author_form/index.md index 6a135187eddc147..98bea69f2c57f4a 100644 --- a/files/en-us/learn_web_development/extensions/server-side/express_nodejs/forms/delete_author_form/index.md +++ b/files/en-us/learn_web_development/extensions/server-side/express_nodejs/forms/delete_author_form/index.md @@ -5,6 +5,8 @@ page-type: learn-module-chapter sidebar: learnsidebar --- +{{PreviousMenuNext("Learn_web_development/Extensions/Server-side/Express_Nodejs/forms/Create_BookInstance_form", "Learn_web_development/Extensions/Server-side/Express_Nodejs/forms/Update_Book_form", "Learn_web_development/Extensions/Server-side/Express_Nodejs/forms")}} + This subarticle shows how to define a page to delete `Author` objects. As discussed in the [form design](/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/forms#form_design) section, our strategy will be to only allow deletion of objects that are not referenced by other objects (in this case that means we won't allow an `Author` to be deleted if it is referenced by a `Book`). @@ -13,11 +15,11 @@ If there are associated books, it should display them, and state that they must ## Controller—get route -Open **/controllers/authorController.js**. Find the exported `author_delete_get()` controller method and replace it with the following code. +Open **controllers/authorController.js**. Find the exported `authorDeleteGet()` controller method and replace it with the following code. ```js // Display Author delete form on GET. -exports.author_delete_get = async (req, res, next) => { +export const authorDeleteGet = async (req, res, next) => { // Get details of author and all their books (in parallel) const [author, allBooksByAuthor] = await Promise.all([ Author.findById(req.params.id).exec(), @@ -56,11 +58,11 @@ When both operations have completed it renders the **author_delete.pug** view, p ## Controller—post route -Find the exported `author_delete_post()` controller method, and replace it with the following code. +Find the exported `authorDeletePost()` controller method, and replace it with the following code. ```js // Handle Author delete on POST. -exports.author_delete_post = async (req, res, next) => { +export const authorDeletePost = async (req, res, next) => { // Get details of author and all their books (in parallel) const [author, allBooksByAuthor] = await Promise.all([ Author.findById(req.params.id).exec(), @@ -77,13 +79,12 @@ exports.author_delete_post = async (req, res, next) => { return; } // Author has no books. Delete object and redirect to the list of authors. - await Author.findByIdAndDelete(req.body.authorid); + await Author.findByIdAndDelete(req.params.id); res.redirect("/catalog/authors"); }; ``` -First we validate that an id has been provided (this is sent via the form body parameters, rather than using the version in the URL). -Then we get the author and their associated books in the same way as for the `GET` route. +First we get the author and their associated books in the same way as for the `GET` route, using the id from the URL. If there are no books then we delete the author object and redirect to the list of all authors. If there are still books then we just re-render the form, passing in the author and list of books to be deleted. @@ -93,7 +94,7 @@ If there are still books then we just re-render the form, passing in the author ## View -Create **/views/author_delete.pug** and copy in the text below. +Create **views/author_delete.pug** and paste in the text below. ```pug extends layout @@ -118,9 +119,6 @@ block content p Do you really want to delete this Author? form(method='POST') - div.form-group - input#authorid.form-control(type='hidden', name='authorid', value=author._id ) - button.btn.btn-primary(type='submit') Delete ``` @@ -129,7 +127,7 @@ It then includes a conditional statement based on the number of **`author_books` - If there _are_ books associated with the author then the page lists the books and states that these must be deleted before this `Author` may be deleted. - If there _are no_ books then the page displays a confirmation prompt. -- If the **Delete** button is clicked then the author id is sent to the server in a `POST` request and that author's record will be deleted. +- If the **Delete** button is clicked then the form sends a `POST` request to the same URL, which includes the author id, and that author's record will be deleted. ## Add a delete control @@ -139,17 +137,17 @@ Next we will add a **Delete** control to the _Author detail_ view (the detail pa > In a full implementation the control would be made visible only to authorized users. > However at this point we haven't got an authorization system in place! -Open the **author_detail.pug** view and add the following lines at the bottom. +Open the **author_detail.pug** view and add the following lines at the end of `block content` (they're indented two spaces to match the rest of the block). ```pug -hr -p - a(href=author.url+'/delete') Delete author + hr + p + a(href=author.url+'/delete') Delete author ``` The control should now appear as a link, as shown below on the _Author detail_ page. -![The Author details section of the Local library application. The left column has a vertical navigation bar. The right section contains the author details with a heading that has the Author's name followed by the life dates of the author and lists the books written by the author below it. There is a button labeled 'Delete Author' at the bottom.](locallibary_express_author_detail_delete.png) +![The Author details section of the Local library application. The left column has a vertical navigation bar. The right section contains the author details with a heading that has the Author's name followed by the life dates of the author and lists the books written by the author below it. There is a link labeled 'Delete author' at the bottom.](locallibary_express_author_detail_delete.png) ## What does it look like? @@ -170,7 +168,4 @@ You can then delete the books from their detail pages (once that code is impleme > The other pages for deleting objects can be implemented in much the same way. > We've left that as a challenge. -## Next steps - -- Return to [Express Tutorial Part 6: Working with forms](/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/forms). -- Proceed to the final subarticle of part 6: [Update Book form](/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/forms/Update_Book_form). +{{PreviousMenuNext("Learn_web_development/Extensions/Server-side/Express_Nodejs/forms/Create_BookInstance_form", "Learn_web_development/Extensions/Server-side/Express_Nodejs/forms/Update_Book_form", "Learn_web_development/Extensions/Server-side/Express_Nodejs/forms")}} diff --git a/files/en-us/learn_web_development/extensions/server-side/express_nodejs/forms/delete_author_form/locallibary_express_author_detail_delete.png b/files/en-us/learn_web_development/extensions/server-side/express_nodejs/forms/delete_author_form/locallibary_express_author_detail_delete.png index 77098b261c63326..2b1ee1dc601afbd 100644 Binary files a/files/en-us/learn_web_development/extensions/server-side/express_nodejs/forms/delete_author_form/locallibary_express_author_detail_delete.png and b/files/en-us/learn_web_development/extensions/server-side/express_nodejs/forms/delete_author_form/locallibary_express_author_detail_delete.png differ diff --git a/files/en-us/learn_web_development/extensions/server-side/express_nodejs/forms/index.md b/files/en-us/learn_web_development/extensions/server-side/express_nodejs/forms/index.md index f7b6c4849c56d4a..b6caff9c594377e 100644 --- a/files/en-us/learn_web_development/extensions/server-side/express_nodejs/forms/index.md +++ b/files/en-us/learn_web_development/extensions/server-side/express_nodejs/forms/index.md @@ -115,10 +115,10 @@ npm install express-validator To use the validator in our controllers, we specify the particular functions we want to import from the [express-validator](https://www.npmjs.com/package/express-validator) module, as shown below: ```js -const { body, validationResult } = require("express-validator"); +import { body, validationResult } from "express-validator"; ``` -There are many functions available, allowing you to check and sanitize data from request parameters, body, headers, cookies, etc., or all of them at once. For this tutorial, we'll primarily be using `body` and `validationResult` (as "required" above). +There are many functions available, allowing you to check and sanitize data from request parameters, body, headers, cookies, etc., or all of them at once. For this tutorial, we'll primarily be using the `body` and `validationResult` functions that we just imported. The functions are defined as below: @@ -203,14 +203,14 @@ For this project we will simplify the implementation by stating that a form can In order to implement our form handling code, we will need two routes that have the same URL pattern. The first (`GET`) route is used to display a new empty form for creating the object. The second route (`POST`) is used for validating data entered by the user, and then saving the information and redirecting to the detail page (if the data is valid) or redisplaying the form with errors (if the data is invalid). -We have already created the routes for all our model's create pages in **/routes/catalog.js** (in a [previous tutorial](/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/routes)). For example, the genre routes are shown below: +We have already created the routes for all our model's create pages in **routes/catalog.js** (in a [previous tutorial](/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/routes)). For example, the genre routes are shown below: ```js // GET request for creating a Genre. NOTE This must come before route that displays Genre (uses id). -router.get("/genre/create", genre_controller.genre_create_get); +router.get("/genre/create", genreController.genreCreateGet); // POST request for creating Genre. -router.post("/genre/create", genre_controller.genre_create_post); +router.post("/genre/create", genreController.genreCreatePost); ``` ## Express forms subarticles @@ -242,7 +242,7 @@ Implement the update pages for the `BookInstance`, `Author`, and `Genre` models, A few tips: - The _Book update page_ we just implemented is the hardest! The same patterns can be used for the update pages for the other objects. -- The `Author` date of death and date of birth fields and the `BookInstance` due_date field are the wrong format to input into the date input field on the form (it requires data in form "YYYY-MM-DD"). The easiest way to get around this is to define a new virtual property for the dates that formats the dates appropriately, and then use this field in the associated view templates. +- The `Author` date of death and date of birth fields and the `BookInstance` `due_back` field are the wrong format to input into the date input field on the form (it requires data in form "YYYY-MM-DD"). The easiest way to get around this is to define a new virtual property for the dates that formats the dates appropriately, and then use this field in the associated view templates. - If you get stuck, there are examples of the update pages in [the example here](https://github.com/mdn/express-locallibrary-tutorial). ## Summary diff --git a/files/en-us/learn_web_development/extensions/server-side/express_nodejs/forms/update_book_form/index.md b/files/en-us/learn_web_development/extensions/server-side/express_nodejs/forms/update_book_form/index.md index 296137b9ad618ca..99282c17c0bcbc0 100644 --- a/files/en-us/learn_web_development/extensions/server-side/express_nodejs/forms/update_book_form/index.md +++ b/files/en-us/learn_web_development/extensions/server-side/express_nodejs/forms/update_book_form/index.md @@ -5,15 +5,17 @@ page-type: learn-module-chapter sidebar: learnsidebar --- +{{PreviousMenu("Learn_web_development/Extensions/Server-side/Express_Nodejs/forms/Delete_author_form", "Learn_web_development/Extensions/Server-side/Express_Nodejs/forms")}} + This final subarticle shows how to define a page to update `Book` objects. Form handling when updating a book is much like that for creating a book, except that you must populate the form in the `GET` route with values from the database. ## Controller—get route -Open **/controllers/bookController.js**. Find the exported `book_update_get()` controller method and replace it with the following code. +Open **controllers/bookController.js**. Find the exported `bookUpdateGet()` controller method and replace it with the following code. ```js // Display book update form on GET. -exports.book_update_get = async (req, res, next) => { +export const bookUpdateGet = async (req, res, next) => { // Get book, authors and genres for form. const [book, allAuthors, allGenres] = await Promise.all([ Book.findById(req.params.id).populate("author").exec(), @@ -54,11 +56,11 @@ We then mark the currently selected genres as checked and then render the **book ## Controller—post route -Find the exported `book_update_post()` controller method, and replace it with the following code. +Find the exported `bookUpdatePost()` controller method, and replace it with the following code. ```js // Handle book update on POST. -exports.book_update_post = [ +export const bookUpdatePost = [ // Convert the genre to an array. (req, res, next) => { if (!Array.isArray(req.body.genre)) { @@ -125,9 +127,9 @@ exports.book_update_post = [ } // Data from form is valid. Update the record. - const updatedBook = await Book.findByIdAndUpdate(req.params.id, book, {}); + await Book.findByIdAndUpdate(req.params.id, book, {}); // Redirect to book detail page. - res.redirect(updatedBook.url); + res.redirect(book.url); }, ]; ``` @@ -137,7 +139,7 @@ First we validate and sanitize the book data from the form and use it to create ## View -There is no need to change the view for the form (**/views/book_form.pug**) as the same template works for both creating and updating the book. +There is no need to change the view for the form (**views/book_form.pug**) as the same template works for both creating and updating the book. ## Add an update button @@ -164,6 +166,4 @@ The form should look just like the _Create book_ page, only with a title of 'Upd > [!NOTE] > The other pages for updating objects can be implemented in much the same way. We've left that as a challenge. -## Next steps - -- Return to [Express Tutorial Part 6: Working with forms](/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/forms). +{{PreviousMenu("Learn_web_development/Extensions/Server-side/Express_Nodejs/forms/Delete_author_form", "Learn_web_development/Extensions/Server-side/Express_Nodejs/forms")}} diff --git a/files/en-us/learn_web_development/extensions/server-side/express_nodejs/introduction/index.md b/files/en-us/learn_web_development/extensions/server-side/express_nodejs/introduction/index.md index b12cf305fa5984b..4603aeb69168ad3 100644 --- a/files/en-us/learn_web_development/extensions/server-side/express_nodejs/introduction/index.md +++ b/files/en-us/learn_web_development/extensions/server-side/express_nodejs/introduction/index.md @@ -31,13 +31,13 @@ In this first Express article we answer the questions "What is Node?" and "What [Node](https://nodejs.org/) (or more formally _Node.js_) is an open-source, cross-platform runtime environment that allows developers to create all kinds of server-side tools and applications in [JavaScript](/en-US/docs/Glossary/JavaScript). The runtime is intended for use outside of a browser context (i.e., running directly on a computer or server OS). As such, the environment omits browser-specific JavaScript APIs and adds support for more traditional OS APIs including HTTP and file system libraries. -From a web server development perspective Node has a number of benefits: +From a web server development perspective, Node has a number of benefits: - Great performance! Node was designed to optimize throughput and scalability in web applications and is a good solution for many common web-development problems (e.g., real-time web applications). - Code is written in "plain old JavaScript", which means that less time is spent dealing with "context shift" between languages when you're writing both client-side and server-side code. -- JavaScript is a relatively new programming language and benefits from improvements in language design when compared to other traditional web-server languages (e.g., Python, PHP, etc.) Many other new and popular languages compile/convert into JavaScript so you can also use TypeScript, CoffeeScript, ClojureScript, Scala, LiveScript, etc. +- JavaScript is a fast-evolving language that benefits from the latest improvements in language design when compared to other traditional web-server languages (e.g., Java, PHP). - The node package manager (npm) provides access to hundreds of thousands of reusable packages. It also has best-in-class dependency resolution and can also be used to automate most of the build toolchain. -- Node.js is portable. It is available on Microsoft Windows, macOS, Linux, Solaris, FreeBSD, OpenBSD, WebOS, and NonStop OS. Furthermore, it is well-supported by many web hosting providers, that often provide specific infrastructure and documentation for hosting Node sites. +- Node.js is portable. It is available on all mainstream operating systems, as well as most web hosting providers. After writing your server, you can be confident that it will run everywhere without extra modification steps. - It has a very active third-party ecosystem and developer community, with lots of people who are willing to help. You can use Node.js to create a simple web server using the Node HTTP package. @@ -53,11 +53,11 @@ The following example creates a web server that listens for any kind of HTTP req cd test-node ``` -3. Using your favorite text editor, create a file called `hello.js` and paste the following code into it: +3. Using your favorite text editor, create a file called `hello.mjs` and paste the following code into it: ```js // Load HTTP module - const http = require("http"); + import http from "node:http"; const hostname = "127.0.0.1"; const port = 8000; @@ -81,7 +81,7 @@ The following example creates a web server that listens for any kind of HTTP req 5. Go back to the terminal and type the following command: ```bash - node hello.js + node hello.mjs ``` Finally, navigate to `http://localhost:8000` in your web browser; you should see the text "**Hello World**" in the upper left of an otherwise empty web page. @@ -91,7 +91,7 @@ Finally, navigate to `http://localhost:8000` in your web browser; you should see ## Web Frameworks -Other common web-development tasks are not directly supported by Node itself. If you want to add specific handling for different HTTP verbs (e.g., `GET`, `POST`, `DELETE`, etc.), separately handle requests at different URL paths ("routes"), serve static files, or use templates to dynamically create the response, Node won't be of much use on its own. You will either need to write the code yourself, or you can avoid reinventing the wheel and use a web framework! +The Node HTTP library only provides the _primitives_. If you want to implement common web idioms, such as different HTTP verbs (e.g., `GET`, `POST`, `DELETE`, etc.), different URL paths ("routes"), static files, or templates for dynamically creating the response, Node won't be of much use on its own. You will either need to write the code yourself, or you can avoid reinventing the wheel and use a web framework! ## Introducing Express @@ -111,7 +111,7 @@ While _Express_ itself is fairly minimalist, developers have created compatible Node was initially released, for Linux only, in 2009. The npm package manager was released in 2010, and native Windows support was added in 2012. Delve into [Wikipedia](https://en.wikipedia.org/wiki/Node.js#History) if you want to know more. -Express was initially released in November 2010 and is currently on major version 5 of the API. You can check out the [changelog](https://expressjs.com/en/changelog/#5.x) for information about changes in the current release, and [GitHub](https://github.com/expressjs/express/blob/master/History.md) for more detailed historical release notes. +Express was initially released in November 2010 and is currently on major version 5 of the API. You can check out the [changelog](https://github.com/expressjs/express/releases) for information about changes in the current release, and [GitHub](https://github.com/expressjs/express/blob/master/History.md) for more detailed historical release notes. ## How popular are Node and Express? @@ -121,6 +121,9 @@ There isn't any readily-available and definitive measure of the popularity of se Based on the number of high profile companies that use Express, the number of people contributing to the codebase, and the number of people providing both free and paid for support, then yes, _Express_ is a popular framework! +> [!NOTE] +> The Node ecosystem is one of the fastest-evolving ones among all programming languages. Express predates most of its competitors and is losing some of its competitive edge in performance, ergonomics, integration with frontend frameworks, etc. However, it has been around for long enough that you will continue to see it everywhere, and most concepts you learn in this tutorial will readily transfer to any new framework you use. + ## Is Express opinionated? Web frameworks often refer to themselves as "opinionated" or "unopinionated". @@ -144,12 +147,14 @@ The following sections explain some of the common things you'll see when working First let's consider the standard Express [Hello World](https://expressjs.com/en/starter/hello-world/) example (we discuss each part of this below, and in the following sections). > [!NOTE] -> If you have Node and Express already installed (or if you install them as shown in the [next article](/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/development_environment)), you can save this code in a text file called **app.js** and run it in a bash command prompt by calling: +> If you have Node and Express already installed (or if you install them as shown in the [next article](/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/development_environment)), add `"type": "module"` to your **package.json**, save this code in a text file called **app.js**, and run it in a bash command prompt by calling: > -> **`node ./app.js`** +> ```bash +> node ./app.js +> ``` ```js -const express = require("express"); +import express from "express"; const app = express(); const port = 3000; @@ -163,20 +168,25 @@ app.listen(port, () => { }); ``` -The first two lines `require()` (import) the express module and create an [Express application](https://expressjs.com/en/5x/api/#app). This object, which is traditionally named `app`, has methods for routing HTTP requests, configuring middleware, rendering HTML views, registering a template engine, and modifying [application settings](https://expressjs.com/en/5x/api/#app.settings.table) that control how the application behaves (e.g., the environment mode, whether route definitions are case sensitive, etc.) +The first two statements import the express module and create an [Express application](https://expressjs.com/en/5x/api/application/). This object, which is traditionally named `app`, has methods for routing HTTP requests, configuring middleware, rendering HTML views, registering a template engine, and modifying [application settings](https://expressjs.com/en/5x/api/application/#application-settings) that control how the application behaves (e.g., the environment mode, whether route definitions are case sensitive, etc.) -The middle part of the code (the three lines starting with `app.get`) shows a _route definition_. The `app.get()` method specifies a callback function that will be invoked whenever there is an HTTP `GET` request with a path (`'/'`) relative to the site root. The callback function takes a request and a response object as arguments, and calls [`send()`](https://expressjs.com/en/5x/api/#res.send) on the response to return the string "Hello World!" +The middle part of the code (the three lines starting with `app.get`) shows a _route definition_. The `app.get()` method specifies a callback function that will be invoked whenever there is an HTTP `GET` request with a path (`'/'`) relative to the site root. The callback function takes a request and a response object as arguments, and calls [`send()`](https://expressjs.com/en/5x/api/response/#ressend) on the response to return the string "Hello World!" The final block starts up the server on a specified port ('3000') and prints a log comment to the console. With the server running, you could go to `localhost:3000` in your browser to see the example response returned. +> [!NOTE] +> [The Express documentation](https://expressjs.com/en/starter/hello-world/) offers instructions for both ECMAScript modules (using `import`/`export` declarations) and CommonJS modules (using `require()` and `module.exports`). ECMAScript modules are the official JavaScript standard, and they're what this tutorial uses. When reading the official documentation, select the "ESM" tab for the code blocks. + ### Importing and creating modules -A module is a JavaScript library/file that you can import into other code using Node's `require()` function. _Express_ itself is a module, as are the middleware and database libraries that we use in our _Express_ applications. +A module is a JavaScript library/file that you can import into other code using an [`import`](/en-US/docs/Web/JavaScript/Reference/Statements/import) declaration. _Express_ itself is a module, as are the middleware and database libraries that we use in our _Express_ applications. + +This tutorial uses [ECMAScript modules (ESM)](/en-US/docs/Web/JavaScript/Guide/Modules). Set `"type": "module"` in your project's **package.json** so that Node treats its **.js** files as ES modules. Read the [Node ESM](https://nodejs.org/api/esm.html) reference to understand more about how ESM work in Node. -The code below shows how we import a module by name, using the _Express_ framework as an example. First we invoke the `require()` function, specifying the name of the module as a string (`'express'`), and calling the returned object to create an [Express application](https://expressjs.com/en/5x/api/#app). We can then access the properties and functions of the application object. +The code below shows how we import a module by name, using the _Express_ framework as an example. We import the module's default export as `express`, then call it to create an [Express application](https://expressjs.com/en/5x/api/application/). We can then access the properties and functions of the application object. ```js -const express = require("express"); +import express from "express"; const app = express(); ``` @@ -186,46 +196,53 @@ You can also create your own modules that can be imported in the same way. > [!NOTE] > You will _want_ to create your own modules, because this allows you to organize your code into manageable parts — a monolithic single-file application is hard to understand and maintain. Using modules also helps you manage your namespace, because only the variables you explicitly export are imported when you use a module. -To make objects available outside of a module you just need to expose them as additional properties on the `exports` object. For example, the **square.js** module below is a file that exports `area()` and `perimeter()` methods: +To make objects available outside of a module, use an [`export`](/en-US/docs/Web/JavaScript/Reference/Statements/export) declaration. For example, the **square.js** module below exports `area()` and `perimeter()` functions: ```js -exports.area = function (width) { +export function area(width) { return width * width; -}; -exports.perimeter = function (width) { +} + +export function perimeter(width) { return 4 * width; -}; +} ``` -We can import this module using `require()`, and then call the exported method(s) as shown: +We can import these named exports and call them as shown: ```js -const square = require("./square"); // Here we require() the name of the file without the (optional) .js file extension +import { area } from "./square.js"; -console.log(`The area of a square with a width of 4 is ${square.area(4)}`); +console.log(`The area of a square with a width of 4 is ${area(4)}`); ``` -> [!NOTE] -> You can also specify an absolute path to the module (or a name, as we did initially). +Relative imports must include the file extension. To access all the named exports through one object, use a namespace import: + +```js +import * as square from "./square.js"; + +console.log( + `The perimeter of a square with a width of 4 is ${square.perimeter(4)}`, +); +``` -If you want to export a complete object in one assignment instead of building it one property at a time, assign it to `module.exports` as shown below (you can also do this to make the root of the exports object a constructor or other function): +You can also export a single value as the module's _default export_: ```js -module.exports = { - area(width) { - return width * width; - }, - - perimeter(width) { - return 4 * width; - }, -}; +export default function area(width) { + return width * width; +} ``` -> [!NOTE] -> You can think of `exports` as a [shortcut](https://nodejs.org/api/modules.html#modules_exports_shortcut) to `module.exports` within a given module. In fact, `exports` is just a variable that gets initialized to the value of `module.exports` before the module is evaluated. That value is a reference to an object (empty object in this case). This means that `exports` holds a reference to the same object referenced by `module.exports`. It also means that by assigning another value to `exports` it's no longer bound to `module.exports`. +Import a default export without braces, choosing a local name for it: + +```js +import squareArea from "./square.js"; + +console.log(squareArea(4)); +``` -For a lot more information about modules see [Modules](https://nodejs.org/api/modules.html#modules_modules) (Node API docs). +For more information see [Modules: ECMAScript modules](https://nodejs.org/api/esm.html) (Node API docs). ### Using asynchronous APIs @@ -268,7 +285,7 @@ app.get("/", (req, res) => { }); ``` -The callback function takes a request and a response object as arguments. In this case, the method calls [`send()`](https://expressjs.com/en/5x/api/#res.send) on the response to return the string "Hello World!" There are a [number of other response methods](https://expressjs.com/en/guide/routing/#response-methods) for ending the request/response cycle, for example, you could call [`res.json()`](https://expressjs.com/en/5x/api/#res.json) to send a JSON response or [`res.sendFile()`](https://expressjs.com/en/5x/api/#res.sendFile) to send a file. +The callback function takes a request and a response object as arguments. In this case, the method calls [`send()`](https://expressjs.com/en/5x/api/response/#ressend) on the response to return the string "Hello World!" There are a [number of other response methods](https://expressjs.com/en/guide/routing/#response-methods) for ending the request/response cycle, for example, you could call [`res.json()`](https://expressjs.com/en/5x/api/response/#resjson) to send a JSON response or [`res.sendFile()`](https://expressjs.com/en/5x/api/response/#ressendfile) to send a file. > [!NOTE] > You can use any argument names you like in the callback functions; when the callback is invoked the first argument will always be the request and the second will always be the response. It makes sense to name them such that you can identify the object you're working with in the body of the callback. @@ -288,14 +305,14 @@ app.all("/secret", (req, res, next) => { Routes allow you to match particular patterns of characters in a URL, and extract some values from the URL and pass them as parameters to the route handler (as attributes of the request object passed as a parameter). -Often it is useful to group route handlers for a particular part of a site together and access them using a common route-prefix (e.g., a site with a Wiki might have all wiki-related routes in one file and have them accessed with a route prefix of _/wiki/_). In _Express_ this is achieved by using the [`express.Router`](https://expressjs.com/en/guide/routing/#express-router) object. For example, we can create our wiki route in a module named **wiki.js**, and then export the `Router` object, as shown below: +Often it is useful to group route handlers for a particular part of a site together and access them using a common route-prefix (e.g., a site with a Wiki might have all wiki-related routes in one file and have them accessed with a route prefix of _/wiki/_). In _Express_ this is achieved by using the [`express.Router`](https://expressjs.com/en/guide/routing/#expressrouter) object. For example, we can create our wiki route in a module named **wiki.js**, and then export the `Router` object, as shown below: ```js // wiki.js - Wiki route module -const express = require("express"); +import { Router } from "express"; -const router = express.Router(); +const router = Router(); // Home page route router.get("/", (req, res) => { @@ -307,16 +324,16 @@ router.get("/about", (req, res) => { res.send("About this wiki"); }); -module.exports = router; +export default router; ``` > [!NOTE] > Adding routes to the `Router` object is just like adding routes to the `app` object (as shown previously). -To use the router in our main app file we would then `require()` the route module (**wiki.js**), then call `use()` on the _Express_ application to add the Router to the middleware handling path. The two routes will then be accessible from `/wiki/` and `/wiki/about/`. +To use the router in our main app file we would then `import` the route module (**wiki.js**), then call `use()` on the _Express_ application to add the Router to the middleware handling path. The two routes will then be accessible from `/wiki/` and `/wiki/about/`. ```js -const wiki = require("./wiki.js"); +import wiki from "./wiki.js"; // … app.use("/wiki", wiki); @@ -343,8 +360,8 @@ npm install morgan You could then call `use()` on the _Express application object_ to add the middleware to the stack: ```js -const express = require("express"); -const logger = require("morgan"); +import express from "express"; +import logger from "morgan"; const app = express(); app.use(logger("dev")); @@ -361,7 +378,7 @@ You can add a middleware function to the processing chain for _all responses_ wi The example below shows how you can add the middleware function using both approaches, and with/without a route. ```js -const express = require("express"); +import express from "express"; const app = express(); @@ -390,7 +407,7 @@ The Express documentation has a lot more excellent documentation about [using](h ### Serving static files -You can use the [express.static](https://expressjs.com/en/5x/api/#express.static) middleware to serve static files, including your images, CSS and JavaScript (`static()` is the only middleware function that is actually **part** of _Express_). For example, you would use the line below to serve images, CSS files, and JavaScript files from a directory named '**public'** at the same level as where you call node: +You can use the [express.static](https://expressjs.com/en/5x/api/express/#expressstatic) middleware to serve static files, including your images, CSS and JavaScript (`static()` is the only middleware function that is actually **part** of _Express_). For example, you would use the line below to serve images, CSS files, and JavaScript files from a directory named '**public'** at the same level as where you call node: ```js app.use(express.static("public")); @@ -412,7 +429,7 @@ app.use(express.static("public")); app.use(express.static("media")); ``` -You can also create a virtual prefix for your static URLs, rather than having the files added to the base URL. For example, here we [specify a mount path](https://expressjs.com/en/5x/api/#app.use) so that the files are loaded with the prefix "/media": +You can also create a virtual prefix for your static URLs, rather than having the files added to the base URL. For example, here we [specify a mount path](https://expressjs.com/en/5x/api/application/#appuse) so that the files are loaded with the prefix "/media": ```js app.use("/media", express.static("public")); @@ -466,7 +483,7 @@ The database itself can be installed locally or on a cloud server. In your Expre The example below shows how you can find "mammal" records using MongoDB: ```js -const { MongoClient } = require("mongodb"); +import { MongoClient } from "mongodb"; const uri = "mongodb://localhost:27017"; const client = new MongoClient(uri); @@ -494,24 +511,23 @@ For more information see [Database integration](https://expressjs.com/en/guide/d Template engines (also referred to as "view engines" in _Express_) allow you to specify the _structure_ of an output document in a template, using placeholders for data that will be filled in when a page is generated. Templates are often used to create HTML, but can also create other types of documents. Express has support for a number of template engines, notably Pug (formerly "Jade"), Mustache, and EJS. Each has its own strengths for addressing particular use cases (relative comparisons can easily be found via Internet search). -The Express application generator uses Jade as its default, but it also supports several others. In your application settings code you set the template engine to use and the location where Express should look for templates using the 'views' and 'view engine' settings, as shown below (you will also have to install the package containing your template library too!) ```js -const express = require("express"); -const path = require("path"); +import express from "express"; +import path from "node:path"; const app = express(); // Set directory to contain the templates ('views') -app.set("views", path.join(__dirname, "views")); +app.set("views", path.join(import.meta.dirname, "views")); // Set view engine to use, in this case 'some_template_engine_name' app.set("view engine", "some_template_engine_name"); ``` -The appearance of the template will depend on what engine you use. Assuming that you have a template file named "index.\" that contains placeholders for data variables named 'title' and "message", you would call [`Response.render()`](https://expressjs.com/en/5x/api/#res.render) in a route handler function to create and send the HTML response: +The appearance of the template will depend on what engine you use. Assuming that you have a template file named "index.\" that contains placeholders for data variables named 'title' and "message", you would call [`Response.render()`](https://expressjs.com/en/5x/api/response/#resrender) in a route handler function to create and send the HTML response: ```js app.get("/", (req, res) => { @@ -525,7 +541,7 @@ For more information see [Using template engines with Express](https://expressjs Express makes no assumptions in terms of structure or what components you use. Routes, views, static files, and other application-specific logic can live in any number of files with any directory structure. While it is perfectly possible to have the whole _Express_ application in one file, typically it makes sense to split your application into files based on function (e.g., account management, blogs, discussion boards) and architectural problem domain (e.g., model, view or controller if you happen to be using an [MVC architecture](/en-US/docs/Glossary/MVC)). -In a later topic we'll use the _Express Application Generator_, which creates a modular app skeleton that we can easily extend for creating web applications. +In a later topic we'll create a modular app skeleton that we can extend for creating web applications. ## Summary @@ -537,7 +553,9 @@ Of course Express is deliberately a very lightweight web application framework, - [Learn Node.js](https://scrimba.com/learn-nodejs-c00ho9qqh6?via=mdn) from Scrimba [_MDN learning partner_](/en-US/docs/MDN/Writing_guidelines/Learning_content#partner_links_and_embeds) provides a fun, interactive introduction to Node.js. - [Learn Express.js](https://scrimba.com/learn-expressjs-c062las154?via=mdn) from Scrimba [_MDN learning partner_](/en-US/docs/MDN/Writing_guidelines/Learning_content#partner_links_and_embeds) builds on top of the previous link, showing how to start using the Express framework to build server-side websites. -- [Modules](https://nodejs.org/api/modules.html#modules_modules) (Node API docs) +- [JavaScript modules](/en-US/docs/Web/JavaScript/Guide/Modules) +- [Modules across platforms](/en-US/docs/Web/JavaScript/Guide/Modules/Modules_across_platforms) +- [ECMAScript modules](https://nodejs.org/api/esm.html) (Node API docs) - [Express](https://expressjs.com/) (home page) - [Basic routing](https://expressjs.com/en/starter/basic-routing/) (Express docs) - [Routing guide](https://expressjs.com/en/guide/routing/) (Express docs) diff --git a/files/en-us/learn_web_development/extensions/server-side/express_nodejs/mongoose/index.md b/files/en-us/learn_web_development/extensions/server-side/express_nodejs/mongoose/index.md index e3ed2c915f5e0c4..353d8e611185c31 100644 --- a/files/en-us/learn_web_development/extensions/server-side/express_nodejs/mongoose/index.md +++ b/files/en-us/learn_web_development/extensions/server-side/express_nodejs/mongoose/index.md @@ -48,7 +48,7 @@ There are two common approaches for interacting with a database: The very best _performance_ can be gained by using SQL, or whatever query language is supported by the database. Object mappers are often slower because they use translation code to map between objects and the database format, which may not use the most efficient database queries (this is particularly true if the mapper supports different database backends, and must make greater compromises in terms of what database features are supported). -The benefit of using an ORM/ODM is that programmers can continue to think in terms of JavaScript objects rather than database semantics — this is particularly true if you need to work with different databases (on either the same or different websites). They also provide an obvious place to perform data validation. +The benefit of using an ORM/ODM is that programmers can continue to think in terms of JavaScript objects rather than database semantics — this is particularly true if you need to work with different databases (on either the same or different websites). They also provide an obvious place to perform data validation, and usually can derive TypeScript types from the data schema. > [!NOTE] > Using ODM/ORMs often results in lower costs for development and maintenance! Unless you're very familiar with the native query language or performance is paramount, you should strongly consider using an ODM. @@ -59,15 +59,21 @@ There are many ODM/ORM solutions available on the npm package manager site (chec A few solutions that were popular at the time of writing are: -- [Mongoose](https://www.npmjs.com/package/mongoose): Mongoose is a [MongoDB](https://www.mongodb.com/) object modeling tool designed to work in an asynchronous environment. -- [Waterline](https://www.npmjs.com/package/waterline): An ORM extracted from the Express-based [Sails](https://sailsjs.com/) web framework. It provides a uniform API for accessing numerous different databases, including Redis, MySQL, LDAP, MongoDB, and Postgres. -- [Bookshelf](https://www.npmjs.com/package/bookshelf): Features both promise-based and traditional callback interfaces, providing transaction support, eager/nested-eager relation loading, polymorphic associations, and support for one-to-one, one-to-many, and many-to-many relations. Works with PostgreSQL, MySQL, and SQLite3. -- [Objection](https://www.npmjs.com/package/objection): Makes it as easy as possible to use the full power of SQL and the underlying database engine (supports SQLite3, Postgres, and MySQL). -- [Sequelize](https://www.npmjs.com/package/sequelize) is a promise-based ORM for Node.js and io.js. It supports the dialects PostgreSQL, MySQL, MariaDB, SQLite, and MSSQL and features solid transaction support, relations, read replication and more. -- [Node ORM2](https://node-orm.readthedocs.io/en/latest/) is an Object Relationship Manager for Node.js. It supports MySQL, SQLite, and Postgres, helping to work with the database using an object-oriented approach. -- [GraphQL](https://graphql.org/): Primarily a query language for restful APIs, GraphQL is very popular, and has features available for reading data from databases. +- [Mongoose](https://mongoosejs.com/): Mongoose is a [MongoDB](https://www.mongodb.com/) object modeling tool designed to work in an asynchronous environment. +- [Prisma ORM](https://www.prisma.io/orm): Defines models in a dedicated schema file and generates a database client from them. This gives you autocomplete and type checking for queries against your own models, while migration tools help keep the database structure in sync with the schema. +- [Drizzle ORM](https://orm.drizzle.team/docs/overview): Defines schemas directly in TypeScript and provides a query API that closely follows SQL. This lets developers familiar with SQL reuse that knowledge to write joins and other queries while getting inferred TypeScript types, without generating a separate database client. +- [TypeORM](https://typeorm.io/docs/guides/active-record-data-mapper/): Maps database records to JavaScript or TypeScript classes. You can put query methods on the model classes themselves (Active Record), or keep database access in separate repositories (Data Mapper), giving you a choice of how to organize persistence and application logic. +- [Sequelize](https://sequelize.org/): A promise-based ORM for Node.js and TypeScript. It supports the dialects PostgreSQL, MySQL, MariaDB, SQLite, and MSSQL and features solid transaction support, relations, read replication and more. +- [GraphQL](https://graphql.org/): A query language for APIs, often used as an alternative to REST. A GraphQL server gets its data through resolver functions, which can use a database driver or an ORM. -As a general rule, you should consider both the features provided and the "community activity" (downloads, contributions, bug reports, quality of documentation, etc.) when selecting a solution. At the time of writing Mongoose is by far the most popular ODM, and is a reasonable choice if you're using MongoDB for your database. +As a general rule, you should consider both the features provided and the "community activity" (downloads, contributions, bug reports, quality of documentation, etc.) when selecting a solution. Some other things to consider: + +- Does the ORM require writing a separate schema declaration file, and does it need extra compilation steps to get the JavaScript glue code? +- Does it automatically generate strict TypeScript types? +- Is it performant enough for the application? +- Can it adequately describe the application's data model? + +At the time of writing, Mongoose is a reasonable choice when using MongoDB for your database. ### Using Mongoose and MongoDB for the LocalLibrary @@ -200,11 +206,10 @@ Installing _Mongoose_ adds all its dependencies, including the MongoDB database ### Connecting to MongoDB _Mongoose_ requires a connection to a MongoDB database. -You can `require()` and connect to a locally hosted database with `mongoose.connect()` as shown below (for the tutorial we'll instead connect to an internet-hosted database). +You can import Mongoose and connect to a locally hosted database with `mongoose.connect()` as shown below (for the tutorial we'll instead connect to an internet-hosted database). ```js -// Import the mongoose module -const mongoose = require("mongoose"); +import mongoose from "mongoose"; // Define the database URL to connect to. const mongoDB = "mongodb://127.0.0.1/my_database"; @@ -236,11 +241,10 @@ Schemas are then "compiled" into models using the `mongoose.model()` method. Onc #### Defining schemas -The code fragment below shows how you might define a simple schema. First you `require()` mongoose, then use the Schema constructor to create a new schema instance, defining the various fields inside it in the constructor's object parameter. +The code fragment below shows how you might define a simple schema. First you import mongoose, then use the Schema constructor to create a new schema instance, defining the various fields inside it in the constructor's object parameter. ```js -// Require Mongoose -const mongoose = require("mongoose"); +import mongoose from "mongoose"; // Define a schema const Schema = mongoose.Schema; @@ -478,7 +482,7 @@ Each story can have a single author. The `ref` property tells the schema which model can be assigned to this field. ```js -const mongoose = require("mongoose"); +import mongoose from "mongoose"; const Schema = mongoose.Schema; @@ -539,14 +543,14 @@ This is almost everything you need to know about working with related items _for ### One schema/model per file -While you can create schemas and models using any file structure you like, we highly recommend defining each model schema in its own module (file), then exporting the method to create the model. +While you can create schemas and models using any file structure you like, we highly recommend defining each model schema in its own module (file), then exporting the model. This is shown below: ```js // File: ./models/some-model.js -// Require Mongoose -const mongoose = require("mongoose"); +// Import Mongoose +import mongoose from "mongoose"; // Define a schema const Schema = mongoose.Schema; @@ -556,15 +560,15 @@ const SomeModelSchema = new Schema({ a_date: Date, }); -// Export function to create "SomeModel" model class -module.exports = mongoose.model("SomeModel", SomeModelSchema); +// Export model +export default mongoose.model("SomeModel", SomeModelSchema); ``` -You can then require and use the model immediately in other files. Below we show how you might use it to get all instances of the model. +You can then import and use the model immediately in other files. Below we show how you might use it to get all instances of the model. ```js -// Create a SomeModel model just by requiring the module -const SomeModel = require("../models/some-model"); +// Import the SomeModel model +import SomeModel from "../models/some-model.js"; // Use the SomeModel object (model) to find all SomeModel records const modelInstances = await SomeModel.find().exec(); @@ -670,97 +674,60 @@ npm install mongoose ## Connect to MongoDB -Open **bin/www** (from the root of your project) and copy the following text below where you set the port (after the line `app.set("port", port);`). -Replace the database URL string ('_insert_your_database_url_here_') with the location URL representing your own database (i.e., using the information from _MongoDB Atlas_). +Open **server.js** in the root of your project and add the Mongoose import alongside the other package imports at the top of the file: ```js -// Set up mongoose connection -const mongoose = require("mongoose"); - -const mongoDB = "insert_your_database_url_here"; - -connectMongoose() - .then(startServer) - .catch((err) => { - console.error("Failed to connect to MongoDB:", err); - process.exit(1); - }); - -async function connectMongoose() { - await mongoose.connect(mongoDB); - - // Add connection error handlers - mongoose.connection.on("error", (err) => { - console.error("MongoDB connection error:", err); - }); - - mongoose.connection.on("disconnected", () => { - console.warn("MongoDB disconnected"); - }); -} +import mongoose from "mongoose"; ``` -As discussed in the [Mongoose primer](#connecting_to_mongodb) above, this code creates the default connection to the database and reports any errors to the console. -It also calls a `startServer()` function once the connection succeeds, which we'll create next. - -The generated **bin/www** file creates the HTTP server and starts it listening immediately, regardless of whether the database connection succeeds. -Find this code, further down in the same file: +Then add the following code after `app.set("port", port);` and before `const server = createServer(app);`. Replace the database URL string (`"insert_your_database_url_here"`) with the URL for your database from _MongoDB Atlas_. ```js -/** - * Create HTTP server. - */ +const mongoDB = "insert_your_database_url_here"; -var server = http.createServer(app); +mongoose.connection.on("error", (err) => { + console.error("MongoDB connection error:", err); +}); -/** - * Listen on provided port, on all network interfaces. - */ +mongoose.connection.on("disconnected", () => { + console.warn("MongoDB disconnected"); +}); -server.listen(port); -server.on("error", onError); -server.on("listening", onListening); +await mongoose.connect(mongoDB); ``` -Replace it with the following, which moves server creation and listening into a `startServer()` function so that it only runs once `connectMongoose()` has resolved: - -```js -/** - * Create HTTP server and listen on provided port, on all network - * interfaces, once the MongoDB connection is established. - */ - -var server; - -function startServer() { - server = http.createServer(app); - - server.listen(port); - server.on("error", onError); - server.on("listening", onListening); -} -``` +As discussed in the [Mongoose primer](#connecting_to_mongodb) above, this creates the default connection and reports connection errors. Because **server.js** is an ES module, it can use [top-level `await`](/en-US/docs/Web/JavaScript/Reference/Operators/await#top_level_await). Node waits for the connection before continuing to the server creation and listening code. If the initial connection fails, the module fails to load and Node exits without starting the HTTP server. > [!NOTE] -> We could have put the database connection code in our **app.js** code. -> Putting it in the application entry point decouples the application and database, which makes it easier to use a different database for running test code. +> Keeping the database connection in **server.js** allows **app.js** to configure and export the application without connecting to a database or starting a server. -Note that hard-coding database credentials in source code as shown above is not recommended. -We do it here because it shows the core connection code, and because during development there is no significant risk that leaking these details will expose or corrupt sensitive information. -We'll show you how to do this more safely when [deploying to production](/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/deployment#database_configuration)! +> [!WARNING] +> We are hardcoding the database credentials in the source code, which is extremely bad practice. +> We do it here because it shows the core connection code, and because during development there is no significant risk that leaking these details will expose or corrupt sensitive information. +> If you are committing and pushing your code to GitHub, **stop committing right now** until we finish this tutorial; if you commit the code, your database credentials will remain forever in the git history, and will be available to anyone who has access to your GitHub repository. +> We'll show you how to do this more safely when [deploying to production](/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/deployment#database_configuration)! +> +> If you ever accidentally leak your database credentials in your published source code, immediately switch your database password. -## Defining the LocalLibrary Schema +## Defining the LocalLibrary schema We will define a separate module for each model, as [discussed above](#one_schemamodel_per_file). -Start by creating a folder for our models in the project root (**/models**) and then create separate files for each of the models: +Start by creating a folder for our models in the project root (**models/**) and then create separate files for each of the models: ```plain -/express-locallibrary-tutorial # the project root - /models - author.js - book.js - bookinstance.js - genre.js +express-locallibrary-tutorial +├── models +│ ├── author.js +│ ├── book.js +│ ├── bookinstance.js +│ └── genre.js +... +``` + +If you are using Bash or a similar shell, you can create them all with this command: + +```bash +mkdir models && touch models/{author,book,bookinstance,genre}.js ``` ### Author model @@ -769,7 +736,7 @@ Copy the `Author` schema code shown below and paste it into your **./models/auth The schema defines an author as having `String` SchemaTypes for the first and family names (required, with a maximum of 100 characters), and `Date` fields for the dates of birth and death. ```js -const mongoose = require("mongoose"); +import mongoose from "mongoose"; const Schema = mongoose.Schema; @@ -799,7 +766,7 @@ AuthorSchema.virtual("url").get(function () { }); // Export model -module.exports = mongoose.model("Author", AuthorSchema); +export default mongoose.model("Author", AuthorSchema); ``` We've also declared a [virtual](#virtual_properties) for the AuthorSchema named "url" that returns the absolute URL required to get a particular instance of the model — we'll use the property in our templates whenever we need to get a link to a particular author. @@ -817,7 +784,7 @@ Copy the `Book` schema code shown below and paste it into your **./models/book.j Most of this is similar to the author model — we've declared a schema with a number of string fields and a virtual for getting the URL of specific book records, and we've exported the model. ```js -const mongoose = require("mongoose"); +import mongoose from "mongoose"; const Schema = mongoose.Schema; @@ -836,7 +803,7 @@ BookSchema.virtual("url").get(function () { }); // Export model -module.exports = mongoose.model("Book", BookSchema); +export default mongoose.model("Book", BookSchema); ``` The main difference here is that we've created two references to other models: @@ -850,7 +817,7 @@ Finally, copy the `BookInstance` schema code shown below and paste it into your The `BookInstance` represents a specific copy of a book that someone might borrow and includes information about whether the copy is available, on what date it is expected back, and "imprint" (or version) details. ```js -const mongoose = require("mongoose"); +import mongoose from "mongoose"; const Schema = mongoose.Schema; @@ -873,7 +840,7 @@ BookInstanceSchema.virtual("url").get(function () { }); // Export model -module.exports = mongoose.model("BookInstance", BookInstanceSchema); +export default mongoose.model("BookInstance", BookInstanceSchema); ``` The new things we show here are the field options: @@ -905,15 +872,13 @@ In order to test the models (and to create some example books and other items th > [!NOTE] > The code in `populatedb.js` may be useful in learning JavaScript, but understanding it is not necessary for this tutorial. -2. Run the script using node in your command prompt, passing in the URL of your _MongoDB_ database (the same one you replaced the _insert_your_database_url_here_ placeholder with, inside `app.js` earlier): +2. Run the script using node in your command prompt, passing in the URL of your _MongoDB_ database (the same one you replaced the _insert_your_database_url_here_ placeholder with, inside `server.js` earlier): ```bash - node populatedb + node populatedb.js "" ``` - > [!NOTE] - > On Windows you need to wrap the database URL inside double ("). - > On other operating systems you may need single (') quotation marks. + Remember to wrap the URL in double quotes. 3. The script should run through to completion, displaying items as it creates them in the terminal. diff --git a/files/en-us/learn_web_development/extensions/server-side/express_nodejs/routes/index.md b/files/en-us/learn_web_development/extensions/server-side/express_nodejs/routes/index.md index a4471df7eff42ee..d269050f9ff284a 100644 --- a/files/en-us/learn_web_development/extensions/server-side/express_nodejs/routes/index.md +++ b/files/en-us/learn_web_development/extensions/server-side/express_nodejs/routes/index.md @@ -45,13 +45,13 @@ As we've already created the models, the main things we'll need to create are: Ultimately we might have pages to show lists and detail information for books, genres, authors and bookinstances, along with pages to create, update, and delete records. That's a lot to document in one article. Therefore most of this article will concentrate on setting up our routes and controllers to return "dummy" content. We'll extend the controller methods in our subsequent articles to work with model data. -The first section below provides a brief "primer" on how to use the Express [Router](https://expressjs.com/en/5x/api/#router) middleware. We'll then use that knowledge in the following sections when we set up the LocalLibrary routes. +The first section below provides a brief "primer" on how to use the Express [Router](https://expressjs.com/en/5x/api/router/) middleware. We'll then use that knowledge in the following sections when we set up the LocalLibrary routes. ## Routes primer A route is a section of Express code that associates an [HTTP verb](/en-US/docs/Web/HTTP/Reference/Methods) (`GET`, `POST`, `PUT`, `DELETE`, etc.), a URL path/pattern, and a function that is called to handle that pattern. -There are several ways to create routes. For this tutorial we're going to use the [`express.Router`](https://expressjs.com/en/guide/routing/#express-router) middleware as it allows us to group the route handlers for a particular part of a site together and access them using a common route-prefix. We'll keep all our library-related routes in a "catalog" module, and, if we add routes for handling user accounts or other functions, we can keep them grouped separately. +There are several ways to create routes. For this tutorial we're going to use the [`express.Router`](https://expressjs.com/en/guide/routing/#expressrouter) middleware as it allows us to group the route handlers for a particular part of a site together and access them using a common route-prefix. We'll keep all our library-related routes in a "catalog" module, and, if we add routes for handling user accounts or other functions, we can keep them grouped separately. > [!NOTE] > We discussed Express application routes briefly in our [Express Introduction > Creating route handlers](/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/Introduction#creating_route_handlers). Other than providing better support for modularization (as discussed in the first subsection below), using _Router_ is very similar to defining routes directly on the _Express application object_. @@ -62,14 +62,14 @@ The rest of this section provides an overview of how the `Router` can be used to The code below provides a concrete example of how we can create a route module and then use it in an _Express_ application. -First we create routes for a wiki in a module named **wiki.js**. The code first imports the Express application object, uses it to get a `Router` object and then adds a couple of routes to it using the `get()` method. Last of all the module exports the `Router` object. +First we create routes for a wiki in a module named **wiki.js**. The code first imports the `Router` function from Express, uses it to create a router and then adds a couple of routes to it using the `get()` method. Last of all the module exports the `Router` object. ```js // wiki.js - Wiki route module. -const express = require("express"); +import { Router } from "express"; -const router = express.Router(); +const router = Router(); // Home page route. router.get("/", (req, res) => { @@ -81,16 +81,16 @@ router.get("/about", (req, res) => { res.send("About this wiki"); }); -module.exports = router; +export default router; ``` > [!NOTE] > Above we are defining our route handler callbacks directly in the router functions. In the LocalLibrary we'll define these callbacks in a separate controller module. -To use the router module in our main app file we first `require()` the route module (**wiki.js**). We then call `use()` on the _Express_ application to add the Router to the middleware handling path, specifying a URL path of 'wiki'. +To use the router module in our main app file we first `import` the route module (**wiki.js**). We then call `use()` on the _Express_ application to add the Router to the middleware handling path, specifying a URL path of 'wiki'. ```js -const wiki = require("./wiki.js"); +import wiki from "./wiki.js"; // … app.use("/wiki", wiki); @@ -115,7 +115,7 @@ The callback takes three arguments (usually named as shown: `req`, `res`, `next` > > The router function above takes a single callback, but you can specify as many callback arguments as you want, or an array of callback functions. Each function is part of the middleware chain, and will be called in the order it is added to the chain (unless a preceding function completes the request). -The callback function here calls [`send()`](https://expressjs.com/en/5x/api/#res.send) on the response to return the string "About this wiki" when we receive a GET request with the path (`/about`). There are a [number of other response methods](https://expressjs.com/en/guide/routing/#response-methods) for ending the request/response cycle. For example, you could call [`res.json()`](https://expressjs.com/en/5x/api/#res.json) to send a JSON response or [`res.sendFile()`](https://expressjs.com/en/5x/api/#res.sendFile) to send a file. The response method that we'll be using most often as we build up the library is [`render()`](https://expressjs.com/en/5x/api/#res.render), which creates and returns HTML files using templates and data—we'll talk a lot more about that in a later article! +The callback function here calls [`send()`](https://expressjs.com/en/5x/api/response/#ressend) on the response to return the string "About this wiki" when we receive a GET request with the path (`/about`). There are a [number of other response methods](https://expressjs.com/en/guide/routing/#response-methods) for ending the request/response cycle. For example, you could call [`res.json()`](https://expressjs.com/en/5x/api/response/#resjson) to send a JSON response or [`res.sendFile()`](https://expressjs.com/en/5x/api/response/#ressendfile) to send a file. The response method that we'll be using most often as we build up the library is [`render()`](https://expressjs.com/en/5x/api/response/#resrender), which creates and returns HTML files using templates and data—we'll talk a lot more about that in a later article! ### HTTP verbs @@ -227,7 +227,7 @@ This leads to very compact code when working with asynchronous promise-based API For example, the following code uses the `find()` method to query a database and then renders the result. ```js -exports.get("/about", async (req, res, next) => { +router.get("/about", async (req, res, next) => { const successfulResult = await About.find({}).exec(); res.render("about_view", { title: "About", list: successfulResult }); }); @@ -237,7 +237,7 @@ The code below shows the same example using a promise chain. Note that if you wanted to, you could `catch()` the error and implement your own custom handling. ```js -exports.get( +router.get( "/about", // Removed 'async' (req, res, next) => @@ -280,18 +280,20 @@ app.get("/", (req, res, next) => { }); ``` -Lastly, if you're using the older style of asynchronous methods that return an error or result in a callback function, then you need to propagate the error yourself. -The following example shows how. +Lastly, if you're using an older-style asynchronous API that passes an error or result to a callback function, then you need to propagate the error yourself. +The following example shows how, using the callback version of Node's `readFile()` function. ```js +import { readFile } from "node:fs"; + router.get("/about", (req, res, next) => { - About.find({}).exec((err, queryResults) => { + readFile("about.txt", "utf8", (err, text) => { if (err) { // Propagate the error return next(err); } - // Successful, so render - res.render("about_view", { title: "About", list: queryResults }); + // Successful, so send the file contents + res.send(text); }); }); ``` @@ -322,66 +324,73 @@ Next we create our route handler callback functions and route code for all the a Before we define our routes, we'll first create all the dummy/skeleton callback functions that they will invoke. The callbacks will be stored in separate "controller" modules for `Book`, `BookInstance`, `Genre`, and `Author` (you can use any file/module structure, but this seems an appropriate granularity for this project). -Start by creating a folder for our controllers in the project root (**/controllers**) and then create separate controller files/modules for handling each of the models: +Start by creating a folder for our controllers in the project root (**controllers/**) and then create separate controller files/modules for handling each of the models: ```plain -/express-locallibrary-tutorial # the project root - /controllers - authorController.js - bookController.js - bookinstanceController.js - genreController.js +express-locallibrary-tutorial +├── controllers +│ ├── authorController.js +│ ├── bookController.js +│ ├── bookinstanceController.js +│ └── genreController.js +... +``` + +If you are using Bash or a similar shell, you can create them all with this command: + +```bash +mkdir controllers && touch controllers/{authorController,bookController,bookinstanceController,genreController}.js ``` ### Author controller -Open the **/controllers/authorController.js** file and type in the following code: +Open the **controllers/authorController.js** file and paste in the following code: ```js -const Author = require("../models/author"); +import Author from "../models/author.js"; // Display list of all Authors. -exports.author_list = async (req, res, next) => { +export const authorList = async (req, res, next) => { res.send("NOT IMPLEMENTED: Author list"); }; // Display detail page for a specific Author. -exports.author_detail = async (req, res, next) => { +export const authorDetail = async (req, res, next) => { res.send(`NOT IMPLEMENTED: Author detail: ${req.params.id}`); }; // Display Author create form on GET. -exports.author_create_get = async (req, res, next) => { +export const authorCreateGet = async (req, res, next) => { res.send("NOT IMPLEMENTED: Author create GET"); }; // Handle Author create on POST. -exports.author_create_post = async (req, res, next) => { +export const authorCreatePost = async (req, res, next) => { res.send("NOT IMPLEMENTED: Author create POST"); }; // Display Author delete form on GET. -exports.author_delete_get = async (req, res, next) => { +export const authorDeleteGet = async (req, res, next) => { res.send("NOT IMPLEMENTED: Author delete GET"); }; // Handle Author delete on POST. -exports.author_delete_post = async (req, res, next) => { +export const authorDeletePost = async (req, res, next) => { res.send("NOT IMPLEMENTED: Author delete POST"); }; // Display Author update form on GET. -exports.author_update_get = async (req, res, next) => { +export const authorUpdateGet = async (req, res, next) => { res.send("NOT IMPLEMENTED: Author update GET"); }; // Handle Author update on POST. -exports.author_update_post = async (req, res, next) => { +export const authorUpdatePost = async (req, res, next) => { res.send("NOT IMPLEMENTED: Author update POST"); }; ``` -The module first requires the `Author` model that we'll later be using to access and update our data. +The module first imports the `Author` model that we'll later be using to access and update our data. It then exports functions for each of the URLs we wish to handle. Note that the create, update and delete operations use forms, and hence also have additional methods for handling form post requests — we'll discuss those methods in the "forms article" later on. @@ -390,149 +399,149 @@ If a controller function is expected to receive path parameters, these are outpu #### BookInstance controller -Open the **/controllers/bookinstanceController.js** file and copy in the following code (this follows an identical pattern to the `Author` controller module): +Open the **controllers/bookinstanceController.js** file and paste in the following code (this follows an identical pattern to the `Author` controller module): ```js -const BookInstance = require("../models/bookinstance"); +import BookInstance from "../models/bookinstance.js"; // Display list of all BookInstances. -exports.bookinstance_list = async (req, res, next) => { +export const bookInstanceList = async (req, res, next) => { res.send("NOT IMPLEMENTED: BookInstance list"); }; // Display detail page for a specific BookInstance. -exports.bookinstance_detail = async (req, res, next) => { +export const bookInstanceDetail = async (req, res, next) => { res.send(`NOT IMPLEMENTED: BookInstance detail: ${req.params.id}`); }; // Display BookInstance create form on GET. -exports.bookinstance_create_get = async (req, res, next) => { +export const bookInstanceCreateGet = async (req, res, next) => { res.send("NOT IMPLEMENTED: BookInstance create GET"); }; // Handle BookInstance create on POST. -exports.bookinstance_create_post = async (req, res, next) => { +export const bookInstanceCreatePost = async (req, res, next) => { res.send("NOT IMPLEMENTED: BookInstance create POST"); }; // Display BookInstance delete form on GET. -exports.bookinstance_delete_get = async (req, res, next) => { +export const bookInstanceDeleteGet = async (req, res, next) => { res.send("NOT IMPLEMENTED: BookInstance delete GET"); }; // Handle BookInstance delete on POST. -exports.bookinstance_delete_post = async (req, res, next) => { +export const bookInstanceDeletePost = async (req, res, next) => { res.send("NOT IMPLEMENTED: BookInstance delete POST"); }; // Display BookInstance update form on GET. -exports.bookinstance_update_get = async (req, res, next) => { +export const bookInstanceUpdateGet = async (req, res, next) => { res.send("NOT IMPLEMENTED: BookInstance update GET"); }; // Handle bookinstance update on POST. -exports.bookinstance_update_post = async (req, res, next) => { +export const bookInstanceUpdatePost = async (req, res, next) => { res.send("NOT IMPLEMENTED: BookInstance update POST"); }; ``` #### Genre controller -Open the **/controllers/genreController.js** file and copy in the following text (this follows an identical pattern to the `Author` and `BookInstance` files): +Open the **controllers/genreController.js** file and paste in the following text (this follows an identical pattern to the `Author` and `BookInstance` files): ```js -const Genre = require("../models/genre"); +import Genre from "../models/genre.js"; // Display list of all Genre. -exports.genre_list = async (req, res, next) => { +export const genreList = async (req, res, next) => { res.send("NOT IMPLEMENTED: Genre list"); }; // Display detail page for a specific Genre. -exports.genre_detail = async (req, res, next) => { +export const genreDetail = async (req, res, next) => { res.send(`NOT IMPLEMENTED: Genre detail: ${req.params.id}`); }; // Display Genre create form on GET. -exports.genre_create_get = async (req, res, next) => { +export const genreCreateGet = async (req, res, next) => { res.send("NOT IMPLEMENTED: Genre create GET"); }; // Handle Genre create on POST. -exports.genre_create_post = async (req, res, next) => { +export const genreCreatePost = async (req, res, next) => { res.send("NOT IMPLEMENTED: Genre create POST"); }; // Display Genre delete form on GET. -exports.genre_delete_get = async (req, res, next) => { +export const genreDeleteGet = async (req, res, next) => { res.send("NOT IMPLEMENTED: Genre delete GET"); }; // Handle Genre delete on POST. -exports.genre_delete_post = async (req, res, next) => { +export const genreDeletePost = async (req, res, next) => { res.send("NOT IMPLEMENTED: Genre delete POST"); }; // Display Genre update form on GET. -exports.genre_update_get = async (req, res, next) => { +export const genreUpdateGet = async (req, res, next) => { res.send("NOT IMPLEMENTED: Genre update GET"); }; // Handle Genre update on POST. -exports.genre_update_post = async (req, res, next) => { +export const genreUpdatePost = async (req, res, next) => { res.send("NOT IMPLEMENTED: Genre update POST"); }; ``` #### Book controller -Open the **/controllers/bookController.js** file and copy in the following code. +Open the **controllers/bookController.js** file and paste in the following code. This follows the same pattern as the other controller modules, but additionally has an `index()` function for displaying the site welcome page: ```js -const Book = require("../models/book"); +import Book from "../models/book.js"; -exports.index = async (req, res, next) => { +export const index = async (req, res, next) => { res.send("NOT IMPLEMENTED: Site Home Page"); }; // Display list of all books. -exports.book_list = async (req, res, next) => { +export const bookList = async (req, res, next) => { res.send("NOT IMPLEMENTED: Book list"); }; // Display detail page for a specific book. -exports.book_detail = async (req, res, next) => { +export const bookDetail = async (req, res, next) => { res.send(`NOT IMPLEMENTED: Book detail: ${req.params.id}`); }; // Display book create form on GET. -exports.book_create_get = async (req, res, next) => { +export const bookCreateGet = async (req, res, next) => { res.send("NOT IMPLEMENTED: Book create GET"); }; // Handle book create on POST. -exports.book_create_post = async (req, res, next) => { +export const bookCreatePost = async (req, res, next) => { res.send("NOT IMPLEMENTED: Book create POST"); }; // Display book delete form on GET. -exports.book_delete_get = async (req, res, next) => { +export const bookDeleteGet = async (req, res, next) => { res.send("NOT IMPLEMENTED: Book delete GET"); }; // Handle book delete on POST. -exports.book_delete_post = async (req, res, next) => { +export const bookDeletePost = async (req, res, next) => { res.send("NOT IMPLEMENTED: Book delete POST"); }; // Display book update form on GET. -exports.book_update_get = async (req, res, next) => { +export const bookUpdateGet = async (req, res, next) => { res.send("NOT IMPLEMENTED: Book update GET"); }; // Handle book update on POST. -exports.book_update_post = async (req, res, next) => { +export const bookUpdatePost = async (req, res, next) => { res.send("NOT IMPLEMENTED: Book update POST"); }; ``` @@ -545,155 +554,156 @@ The skeleton already has a **./routes** folder containing routes for the _index_ Create another route file — **catalog.js** — inside this folder, as shown. ```plain -/express-locallibrary-tutorial # the project root - /routes - index.js - users.js - catalog.js +express-locallibrary-tutorial +├── routes +│ ├── catalog.js +│ ├── index.js +│ └── users.js +... ``` -Open **/routes/catalog.js** and copy in the code below: +Open **routes/catalog.js** and paste in the code below: ```js -const express = require("express"); +import { Router } from "express"; -// Require controller modules. -const book_controller = require("../controllers/bookController"); -const author_controller = require("../controllers/authorController"); -const genre_controller = require("../controllers/genreController"); -const book_instance_controller = require("../controllers/bookinstanceController"); +// Import controller modules. +import * as bookController from "../controllers/bookController.js"; +import * as authorController from "../controllers/authorController.js"; +import * as genreController from "../controllers/genreController.js"; +import * as bookInstanceController from "../controllers/bookinstanceController.js"; -const router = express.Router(); +const router = Router(); /// BOOK ROUTES /// // GET catalog home page. -router.get("/", book_controller.index); +router.get("/", bookController.index); // GET request for creating a Book. NOTE This must come before routes that display Book (uses id). -router.get("/book/create", book_controller.book_create_get); +router.get("/book/create", bookController.bookCreateGet); // POST request for creating Book. -router.post("/book/create", book_controller.book_create_post); +router.post("/book/create", bookController.bookCreatePost); // GET request to delete Book. -router.get("/book/:id/delete", book_controller.book_delete_get); +router.get("/book/:id/delete", bookController.bookDeleteGet); // POST request to delete Book. -router.post("/book/:id/delete", book_controller.book_delete_post); +router.post("/book/:id/delete", bookController.bookDeletePost); // GET request to update Book. -router.get("/book/:id/update", book_controller.book_update_get); +router.get("/book/:id/update", bookController.bookUpdateGet); // POST request to update Book. -router.post("/book/:id/update", book_controller.book_update_post); +router.post("/book/:id/update", bookController.bookUpdatePost); // GET request for one Book. -router.get("/book/:id", book_controller.book_detail); +router.get("/book/:id", bookController.bookDetail); // GET request for list of all Book items. -router.get("/books", book_controller.book_list); +router.get("/books", bookController.bookList); /// AUTHOR ROUTES /// // GET request for creating Author. NOTE This must come before route for id (i.e. display author). -router.get("/author/create", author_controller.author_create_get); +router.get("/author/create", authorController.authorCreateGet); // POST request for creating Author. -router.post("/author/create", author_controller.author_create_post); +router.post("/author/create", authorController.authorCreatePost); // GET request to delete Author. -router.get("/author/:id/delete", author_controller.author_delete_get); +router.get("/author/:id/delete", authorController.authorDeleteGet); // POST request to delete Author. -router.post("/author/:id/delete", author_controller.author_delete_post); +router.post("/author/:id/delete", authorController.authorDeletePost); // GET request to update Author. -router.get("/author/:id/update", author_controller.author_update_get); +router.get("/author/:id/update", authorController.authorUpdateGet); // POST request to update Author. -router.post("/author/:id/update", author_controller.author_update_post); +router.post("/author/:id/update", authorController.authorUpdatePost); // GET request for one Author. -router.get("/author/:id", author_controller.author_detail); +router.get("/author/:id", authorController.authorDetail); // GET request for list of all Authors. -router.get("/authors", author_controller.author_list); +router.get("/authors", authorController.authorList); /// GENRE ROUTES /// // GET request for creating a Genre. NOTE This must come before route that displays Genre (uses id). -router.get("/genre/create", genre_controller.genre_create_get); +router.get("/genre/create", genreController.genreCreateGet); // POST request for creating Genre. -router.post("/genre/create", genre_controller.genre_create_post); +router.post("/genre/create", genreController.genreCreatePost); // GET request to delete Genre. -router.get("/genre/:id/delete", genre_controller.genre_delete_get); +router.get("/genre/:id/delete", genreController.genreDeleteGet); // POST request to delete Genre. -router.post("/genre/:id/delete", genre_controller.genre_delete_post); +router.post("/genre/:id/delete", genreController.genreDeletePost); // GET request to update Genre. -router.get("/genre/:id/update", genre_controller.genre_update_get); +router.get("/genre/:id/update", genreController.genreUpdateGet); // POST request to update Genre. -router.post("/genre/:id/update", genre_controller.genre_update_post); +router.post("/genre/:id/update", genreController.genreUpdatePost); // GET request for one Genre. -router.get("/genre/:id", genre_controller.genre_detail); +router.get("/genre/:id", genreController.genreDetail); // GET request for list of all Genre. -router.get("/genres", genre_controller.genre_list); +router.get("/genres", genreController.genreList); /// BOOKINSTANCE ROUTES /// // GET request for creating a BookInstance. NOTE This must come before route that displays BookInstance (uses id). router.get( "/bookinstance/create", - book_instance_controller.bookinstance_create_get, + bookInstanceController.bookInstanceCreateGet, ); // POST request for creating BookInstance. router.post( "/bookinstance/create", - book_instance_controller.bookinstance_create_post, + bookInstanceController.bookInstanceCreatePost, ); // GET request to delete BookInstance. router.get( "/bookinstance/:id/delete", - book_instance_controller.bookinstance_delete_get, + bookInstanceController.bookInstanceDeleteGet, ); // POST request to delete BookInstance. router.post( "/bookinstance/:id/delete", - book_instance_controller.bookinstance_delete_post, + bookInstanceController.bookInstanceDeletePost, ); // GET request to update BookInstance. router.get( "/bookinstance/:id/update", - book_instance_controller.bookinstance_update_get, + bookInstanceController.bookInstanceUpdateGet, ); // POST request to update BookInstance. router.post( "/bookinstance/:id/update", - book_instance_controller.bookinstance_update_post, + bookInstanceController.bookInstanceUpdatePost, ); // GET request for one BookInstance. -router.get("/bookinstance/:id", book_instance_controller.bookinstance_detail); +router.get("/bookinstance/:id", bookInstanceController.bookInstanceDetail); // GET request for list of all BookInstance. -router.get("/bookinstances", book_instance_controller.bookinstance_list); +router.get("/bookinstances", bookInstanceController.bookInstanceList); -module.exports = router; +export default router; ``` -The module requires Express and then uses it to create a `Router` object. The routes are all set up on the router, which is then exported. +The module imports the `Router` function from Express and uses it to create a router. The routes are all set up on the router, which is then exported. The routes are defined either using `.get()` or `.post()` methods on the router object. All the paths are defined using strings (we don't use string patterns or regular expressions). @@ -705,7 +715,7 @@ The handler functions are all imported from the controller modules we created in We've set up all our new routes, but we still have a route to the original page. Let's instead redirect this to the new index page that we've created at the path `/catalog`. -Open **/routes/index.js** and replace the existing route with the function below. +Open **routes/index.js** and replace the existing route with the function below. ```js // GET home page. @@ -715,19 +725,19 @@ router.get("/", (req, res) => { ``` > [!NOTE] -> This is our first use of the [redirect()](https://expressjs.com/en/5x/api/#res.redirect) response method. This redirects to the specified page, by default sending HTTP status code "302 Found". You can change the status code returned if needed, and supply either absolute or relative paths. +> This is our first use of the [`redirect()`](https://expressjs.com/en/5x/api/response/#resredirect) response method. This redirects to the specified page, by default sending HTTP status code "302 Found". You can change the status code returned if needed, and supply either absolute or relative paths. ### Update app.js The last step is to add the routes to the middleware chain. We do this in `app.js`. -Open **app.js** and require the catalog route below the other routes (add the third line shown below, underneath the other two that should be already present in the file): +Open **app.js** and import the catalog route below the other routes (add the third line shown below, underneath the other two that should be already present in the file): ```js -const indexRouter = require("./routes/index"); -const usersRouter = require("./routes/users"); -const catalogRouter = require("./routes/catalog"); // Import routes for "catalog" area of site +import indexRouter from "./routes/index.js"; +import usersRouter from "./routes/users.js"; +import catalogRouter from "./routes/catalog.js"; // Import routes for "catalog" area of site ``` Next, add the catalog route to the middleware stack below the other routes (add the third line shown below, underneath the other two that should be already present in the file): @@ -757,10 +767,10 @@ To test the routes, first start the website using your usual approach DEBUG=express-locallibrary-tutorial:* npm start ``` -- If you previously set up [nodemon](/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/skeleton_website#enable_server_restart_on_file_changes), you can instead use: +- To use [automatic server restarts](/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/skeleton_website#running_the_skeleton_website), you can instead use: ```bash - npm run serverstart + npm run devstart ``` Then navigate to a number of LocalLibrary URLs, and verify that you don't get an error page (HTTP 404). A small set of URLs are listed below for your convenience: diff --git a/files/en-us/learn_web_development/extensions/server-side/express_nodejs/skeleton_website/expressgeneratorskeletonwebsite.png b/files/en-us/learn_web_development/extensions/server-side/express_nodejs/skeleton_website/expressgeneratorskeletonwebsite.png deleted file mode 100644 index d9b7bcce9e34416..000000000000000 Binary files a/files/en-us/learn_web_development/extensions/server-side/express_nodejs/skeleton_website/expressgeneratorskeletonwebsite.png and /dev/null differ diff --git a/files/en-us/learn_web_development/extensions/server-side/express_nodejs/skeleton_website/index.md b/files/en-us/learn_web_development/extensions/server-side/express_nodejs/skeleton_website/index.md index 400897ee235cf9b..ce2d61e70eb3f93 100644 --- a/files/en-us/learn_web_development/extensions/server-side/express_nodejs/skeleton_website/index.md +++ b/files/en-us/learn_web_development/extensions/server-side/express_nodejs/skeleton_website/index.md @@ -22,7 +22,7 @@ This second article in our [Express Tutorial](/en-US/docs/Learn_web_development/ Objective: - To be able to start your own new website projects using the Express Application Generator. + To add routes, templates, and server code to an Express project. @@ -30,65 +30,17 @@ This second article in our [Express Tutorial](/en-US/docs/Learn_web_development/ ## Overview -This article shows how you can create a "skeleton" website using the [Express Application Generator](https://expressjs.com/en/starter/generator/) tool, which you can then populate with site-specific routes, views/templates, and database calls. In this case, we'll use the tool to create the framework for our [Local Library website](/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/Tutorial_local_library_website), to which we'll later add all the other code needed by the site. The process is extremely simple, requiring only that you invoke the generator on the command line with a new project name, optionally also specifying the site's template engine and CSS generator. +This article builds on the project configuration from [Setting up a Node development environment](/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/development_environment). We'll add the server, routes, and templates to create the framework for our [Local Library website](/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/Tutorial_local_library_website), to which we'll later add all the other code needed by the site. -The following sections show you how to call the application generator, and provides a little explanation about the different view/CSS options. We'll also explain how the skeleton website is structured. At the end, we'll show how you can run the website to verify that it works. +The following sections explain the choice of view/CSS options, provide the code to paste into each project file, and show how to run the website to verify that it works. -> [!NOTE] -> -> - The _Express Application Generator_ is not the only generator for Express applications, and the generated project is not the only viable way to structure your files and directories. The generated site does however have a modular structure that is easy to extend and understand. For information about a _minimal_ Express application, see [Hello world example](https://expressjs.com/en/starter/hello-world/) (Express docs). -> - The _Express Application Generator_ declares most variables using `var`. -> We have changed most of these to [`const`](/en-US/docs/Web/JavaScript/Reference/Statements/const) (and a few to [`let`](/en-US/docs/Web/JavaScript/Reference/Statements/let)) in the tutorial, because we want to demonstrate modern JavaScript practice. -> - This tutorial uses the version of _Express_ and other dependencies that are defined in the **package.json** created by the _Express Application Generator_. -> These are not (necessarily) the latest version, and you should update them when deploying a real application to production. - -## Using the application generator - -You should already have installed the generator as part of [setting up a Node development environment](/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/development_environment). As a quick reminder, you install the generator tool site-wide using the npm package manager, as shown: - -```bash -npm install express-generator -g -``` - -The generator has a number of options, which you can view on the command line using the `--help` (or `-h`) command: - -```bash -> express --help - - Usage: express [options] [dir] - - Options: - - --version output the version number - -e, --ejs add ejs engine support - --pug add pug engine support - --hbs add handlebars engine support - -H, --hogan add hogan.js engine support - -v, --view add view support (dust|ejs|hbs|hjs|jade|pug|twig|vash) (defaults to jade) - --no-view use static html instead of view engine - -c, --css add stylesheet support (less|stylus|compass|sass) (defaults to plain CSS) - --git add .gitignore - -f, --force force on non-empty directory - -h, --help output usage information -``` - -You can specify express to create a project inside the _current_ directory using the _Jade_ view engine and plain CSS (if you specify a directory name then the project will be created in a sub-folder with that name). - -```bash -express -``` +## Choosing the project components -You can also choose a view (template) engine using `--view` and/or a CSS generation engine using `--css`. - -> [!NOTE] -> The other options for choosing template engines (e.g., `--hogan`, `--ejs`, `--hbs` etc.) are deprecated. Use `--view` (or `-v`). +In this tutorial, we've made all the decisions for you about which library to use for each task. In your own project, you will need to make the decisions yourself, so we offer a basic overview about the ecosystem landscape. The [Package management](/en-US/docs/Learn_web_development/Extensions/Client-side_tools/Package_management) tutorial has a higher-level explanation of the aspects to consider. ### What view engine should I use? -The _Express Application Generator_ allows you to configure a number of popular view/templating engines, including [EJS](https://www.npmjs.com/package/ejs), [Hbs](https://github.com/pillarjs/hbs), [Pug](https://pugjs.org/api/getting-started.html) (Jade), [Twig](https://www.npmjs.com/package/twig), and [Vash](https://www.npmjs.com/package/vash), although it chooses Jade by default if you don't specify a view option. Express itself can also support a large number of other templating languages [out of the box](https://github.com/expressjs/express/wiki#template-engines). - -> [!NOTE] -> If you want to use a template engine that isn't supported by the generator then see [Using template engines with Express](https://expressjs.com/en/guide/using-template-engines/) (Express docs) and the documentation for your target view engine. +Express supports a number of popular view/templating engines, including [EJS](https://www.npmjs.com/package/ejs), [Hbs](https://github.com/pillarjs/hbs), and [Pug](https://pugjs.org/api/getting-started.html). For information about configuring a template engine, see [Using template engines with Express](https://expressjs.com/en/guide/using-template-engines/) (Express docs) and the documentation for your target view engine. Generally speaking, you should select a templating engine that delivers all the functionality you need and allows you to be productive sooner — or in other words, in the same way that you choose any other component! Some of the things to consider when comparing template engines: @@ -108,389 +60,148 @@ Generally speaking, you should select a templating engine that delivers all the > [!NOTE] > There are many resources on the Internet to help you compare the different options! -For this project, we'll use the [Pug](https://pugjs.org/api/getting-started.html) templating engine (previously called "Jade"), as this is one of the most popular Express/JavaScript templating languages and is supported out of the box by the generator. +For this project, we'll use the [Pug](https://pugjs.org/api/getting-started.html) templating engine (previously called "Jade"), which we installed in the development environment tutorial. ### What CSS stylesheet engine should I use? -The _Express Application Generator_ allows you to create a project that is configured to use the most common CSS stylesheet engines: [LESS](https://lesscss.org/), [SASS](https://sass-lang.com/), [Stylus](https://stylus-lang.com/). +You can configure an Express project to use CSS stylesheet engines such as [LESS](https://lesscss.org/), [SASS](https://sass-lang.com/), and [Stylus](https://stylus-lang.com/). > [!NOTE] > CSS has some limitations that make certain tasks difficult. CSS stylesheet engines allow you to use more powerful syntax for defining your CSS and then compile the definition into plain-old CSS for browsers to use. -As with templating engines, you should use the stylesheet engine that will allow your team to be most productive. For this project, we'll use vanilla CSS (the default) as our CSS requirements are not sufficiently complicated to justify using anything else. +As with templating engines, you should use the stylesheet engine that will allow your team to be most productive. For this project, we'll use vanilla CSS as our CSS requirements are not sufficiently complicated to justify using anything else. ### What database should I use? -The generated code doesn't use/include any databases. _Express_ apps can use any [database mechanism](https://expressjs.com/en/guide/database-integration/) supported by _Node_ (_Express_ itself doesn't define any specific additional behavior/requirements for database management). +The code we'll add in this chapter doesn't use a database. _Express_ apps can use any [database mechanism](https://expressjs.com/en/guide/database-integration/) supported by _Node_ (_Express_ itself doesn't define any specific additional behavior/requirements for database management). We'll discuss how to integrate with a database in a later article. -## Creating the project - -For the sample _Local Library_ app we're going to build, we'll create a project named _express-locallibrary-tutorial_ using the _Pug_ template library and no CSS engine. +## Adding the application files -First, navigate to where you want to create the project and then run the _Express Application Generator_ in the command prompt as shown: - -```bash -express express-locallibrary-tutorial --view=pug -``` - -The generator will create (and list) the project's files. +Open the **express-locallibrary-tutorial** directory you created in [Setting up a Node development environment](/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/development_environment). It already contains **package.json**, **package-lock.json**, **.gitignore**, and the installed dependencies in **node_modules**. Keep those files and settings; we'll now add the application code to that project. ```plain - create : express-locallibrary-tutorial\ - create : express-locallibrary-tutorial\public\ - create : express-locallibrary-tutorial\public\javascripts\ - create : express-locallibrary-tutorial\public\images\ - create : express-locallibrary-tutorial\public\stylesheets\ - create : express-locallibrary-tutorial\public\stylesheets\style.css - create : express-locallibrary-tutorial\routes\ - create : express-locallibrary-tutorial\routes\index.js - create : express-locallibrary-tutorial\routes\users.js - create : express-locallibrary-tutorial\views\ - create : express-locallibrary-tutorial\views\error.pug - create : express-locallibrary-tutorial\views\index.pug - create : express-locallibrary-tutorial\views\layout.pug - create : express-locallibrary-tutorial\app.js - create : express-locallibrary-tutorial\package.json - create : express-locallibrary-tutorial\bin\ - create : express-locallibrary-tutorial\bin\www - - change directory: - > cd express-locallibrary-tutorial - - install dependencies: - > npm install - - run the app (Bash (Linux or macOS)) - > DEBUG=express-locallibrary-tutorial:* npm start - - run the app (PowerShell (Windows)) - > $env:DEBUG = "express-locallibrary-tutorial:*"; npm start - - run the app (Command Prompt (Windows)): - > SET DEBUG=express-locallibrary-tutorial:* & npm start +express-locallibrary-tutorial +├── .gitignore +├── node_modules +│ └── [A lot of installed dependency files] +├── package-lock.json +└── package.json ``` -At the end of the output, the generator provides instructions on how to install the dependencies (as listed in the **package.json** file) and how to run the application on different operating systems. - -> [!NOTE] -> The generator-created files define all variables as `var`. -> Open all of the generated files and change the `var` declarations to `const` before you continue (the remainder of the tutorial assumes that you have done so). - -## Running the skeleton website - -At this point, we have a complete skeleton project. The website doesn't actually _do_ very much yet, but it's worth running it to show that it works. - -1. First, install the dependencies (the `install` command will fetch all the dependency packages listed in the project's **package.json** file). - - ```bash - cd express-locallibrary-tutorial - npm install - ``` - -2. Then run the application. - - On the Windows CMD prompt, use this command: - - ```batch - SET DEBUG=express-locallibrary-tutorial:* & npm start - ``` - - - On Windows PowerShell, use this command: - - ```powershell - $env:DEBUG = "express-locallibrary-tutorial:*"; npm start - ``` - - > [!NOTE] - > PowerShell commands are not covered in this tutorial (The provided "Windows" commands assume you're using the Windows CMD prompt.) - - - On macOS or Linux, use this command: - - ```bash - DEBUG=express-locallibrary-tutorial:* npm start - ``` - -3. Then load `http://localhost:3000/` in your browser to access the app. - -You should see a browser page that looks like this: - -![Browser for default Express app generator website](expressgeneratorskeletonwebsite.png) - -Congratulations! You now have a working Express application that can be accessed via port 3000. - -> [!NOTE] -> You could also start the app just using the `npm start` command. Specifying the DEBUG variable as shown enables console logging/debugging. For example, when you visit the above page you'll see debug output like this: -> -> ```bash -> SET DEBUG=express-locallibrary-tutorial:* & npm start -> ``` -> -> ```plain -> > express-locallibrary-tutorial@0.0.0 start D:\github\mdn\test\exprgen\express-locallibrary-tutorial -> > node ./bin/www -> -> express-locallibrary-tutorial:server Listening on port 3000 +0ms -> GET / 304 490.296 ms - - -> GET /stylesheets/style.css 200 4.886 ms - 111 -> ``` - -## Enable server restart on file changes - -Any changes you make to your Express website are currently not visible until you restart the server. It quickly becomes very irritating to have to stop and restart your server every time you make a change, so it is worth taking the time to automate restarting the server when needed. +### Directory structure -A convenient tool for this purpose is [nodemon](https://github.com/remy/nodemon). This is usually installed globally (as it is a "tool"), but here we'll install and use it locally as a _developer dependency_, so that any developers working with the project get it automatically when they install the application. Use the following command in the root directory for the skeleton project: +Create the following files (all empty text files): -```bash -npm install --save-dev nodemon -``` +- **app.js** +- **public/stylesheets/style.css** +- **routes/index.js** +- **routes/users.js** +- **server.js** +- **views/error.pug** +- **views/index.pug** +- **views/layout.pug** -If you still choose to install [nodemon](https://github.com/remy/nodemon) globally to your machine, and not only to your project's **package.json** file: +If you are using Bash or a similar shell, you can create them all with this command: ```bash -npm install -g nodemon +mkdir -p public/stylesheets routes views && touch app.js public/stylesheets/style.css routes/{index,users}.js server.js views/{error,index,layout}.pug ``` -If you open your project's **package.json** file you'll now see a new section with this dependency: - -```json -{ - "devDependencies": { - "nodemon": "^3.1.10" - } -} -``` - -Because the tool isn't installed globally, we can't launch it from the command line (unless we add it to the path). However, we can call it from an npm script because npm knows which packages are installed. Find the `scripts` section of your **package.json**. Initially, it will contain one line, which begins with `"start"`. Update it by putting a comma at the end of that line, and adding the `"devstart"` and `"serverstart"` lines: - -- On Linux and macOS, the scripts section will look like this: - - ```json - { - "scripts": { - "start": "node ./bin/www", - "devstart": "nodemon ./bin/www", - "serverstart": "DEBUG=express-locallibrary-tutorial:* npm run devstart" - } - } - ``` - -- On Windows, the "serverstart" value would instead look like this (if using the command prompt): - - ```bash - "serverstart": "SET DEBUG=express-locallibrary-tutorial:* & npm run devstart" - ``` - -We can now start the server in almost exactly the same way as previously, but using the `devstart` command. - -> [!NOTE] -> Now if you edit any file in the project the server will restart (or you can restart it by typing `rs` on the command prompt at any time). You will still need to reload the browser to refresh the page. -> -> We now have to call `npm run ` rather than just `npm start`, because "start" is actually an npm command that is mapped to the named script. We could have replaced the command in the _start_ script but we only want to use _nodemon_ during development, so it makes sense to create a new script command. -> -> The `serverstart` command added to the scripts in the **package.json** above is a very good example. Using this approach means you no longer have to type a long command to start the server. Note that the particular command added to the script works for macOS or Linux only. - -## The generated project - -Let's now take a look at the project we just created. -We'll be making some minor modifications to this as we go along. - -### Directory structure - -The generated project, now that you have installed dependencies, has the following file structure (files are the items **not** prefixed with "/"). -The **package.json** file defines the application dependencies and other information. -It also defines a startup script that will call the application entry point, the JavaScript file **/bin/www**. -This sets up some of the application error handling and then loads **app.js** to do the rest of the work. -The app routes are stored in separate modules under the **routes/** directory. -The templates are stored under the /**views** directory. +Your project directory should now look like the following: ```plain express-locallibrary-tutorial - app.js - /bin - www - package.json - package-lock.json - /node_modules - [about 6700 subdirectories and files] - /public - /images - /javascripts - /stylesheets - style.css - /routes - index.js - users.js - /views - error.pug - index.pug - layout.pug +├── .gitignore +├── app.js +├── node_modules +│ └── [A lot of installed dependency files] +├── package-lock.json +├── package.json +├── public +│ └── stylesheets +│ └── style.css +├── routes +│ ├── index.js +│ └── users.js +├── server.js +└── views + ├── error.pug + ├── index.pug + └── layout.pug ``` -The following sections describe the files in a little more detail. - -### package.json - -The **package.json** file defines the application dependencies and other information: - -```json -{ - "name": "express-locallibrary-tutorial", - "version": "0.0.0", - "private": true, - "scripts": { - "start": "node ./bin/www" - }, - "dependencies": { - "cookie-parser": "~1.4.4", - "debug": "~2.6.9", - "express": "~4.16.1", - "http-errors": "~1.6.3", - "morgan": "~1.9.1", - "pug": "2.0.0-beta11" - }, - "devDependencies": { - "nodemon": "^3.1.10" - } -} -``` - -The scripts section first defines a "_start_" script, which is what we are invoking when we call `npm start` to start the server (this script was added by the _Express Application Generator_). From the script definition, you can see that this actually starts the JavaScript file **./bin/www** with _node_. - -We already modified this section in [Enable server restart on file changes](#enable_server_restart_on_file_changes) by adding the _devstart_ and _serverstart_ scripts. -These can be used to start the same **./bin/www** file with _nodemon_ rather than _node_ (this version of the scripts is for Linux and macOS, as discussed above). - -```json -{ - "scripts": { - "start": "node ./bin/www", - "devstart": "nodemon ./bin/www", - "serverstart": "DEBUG=express-locallibrary-tutorial:* npm run devstart" - } -} -``` - -The dependencies include the _express_ package and the package for our selected view engine (_pug_). -In addition, we have the following packages that are useful in many web applications: - -- [cookie-parser](https://www.npmjs.com/package/cookie-parser): Used to parse the cookie header and populate `req.cookies` (essentially provides a convenient method for accessing cookie information). -- [debug](https://www.npmjs.com/package/debug): A tiny node debugging utility modeled after node core's debugging technique. -- [morgan](https://www.npmjs.com/package/morgan): An HTTP request logger middleware for node. -- [http-errors](https://www.npmjs.com/package/http-errors): Create HTTP errors where needed (for express error handling). - -The default versions in the generated project are a little out of date. -Replace the dependencies section of your `package.json` file with the following text, which specifies the latest versions of these libraries at the time of writing: - -```json -{ - "dependencies": { - "cookie-parser": "^1.4.7", - "debug": "^4.4.1", - "express": "^5.1.0", - "http-errors": "~2.0.0", - "morgan": "^1.10.0", - "pug": "3.0.3" - } -} -``` - -Then update your installed dependencies using the command: - -```bash -npm install -``` +The app routes are stored in separate modules under the **routes/** directory. +The templates are stored under the **views/** directory. -> [!NOTE] -> It is a good idea to regularly update to the latest compatible versions of your dependency libraries — this may even be done automatically or semi-automatically as part of a {{glossary("continuous integration")}} setup. -> -> Usually library updates to the minor and patch version remain compatible. -> We've prefixed each version with `^` above so that we can automatically update to the latest `minor.patch` version by running: -> -> ```bash -> npm update --save -> ``` -> -> Major versions change the compatibility. -> For those updates we'll need to manually update the `package.json` and code that uses the library, and extensively re-test the project. +The following sections set up each file. -### www file +### server.js -The file **/bin/www** is the application entry point! The very first thing this does is `require()` the "real" application entry point (**app.js**, in the project root) that sets up and returns the [`express()`](https://expressjs.com/en/api/) application object. -`require()` is the [CommonJS way](https://nodejs.org/api/modules.html) to import JavaScript code, JSON, and other files into the current file. -Here we specify **app.js** module using a relative path and omit the optional (.**js**) file extension. +The file **server.js** is the application entry point! Paste the following into the file: ```js -#!/usr/bin/env node +import { createServer } from "node:http"; +import createDebug from "debug"; -/** - * Module dependencies. - */ +import app from "./app.js"; -const app = require("../app"); -``` +const debug = createDebug("express-locallibrary-tutorial:server"); +const port = Number(process.env.PORT ?? 3000); +if (!Number.isInteger(port) || port < 0 || port > 65535) + throw new RangeError("PORT must be an integer between 0 and 65535"); +app.set("port", port); -> [!NOTE] -> Node.js 14 and later support ES6 `import` statements for importing JavaScript (ECMAScript) modules. -> To use this feature you have to add `"type": "module"` to your Express **package.json** file, all the modules in your application have to use `import` rather than `require()`, and for _relative imports_ you must include the file extension (for more information see the [Node documentation](https://nodejs.org/api/esm.html#introduction)). -> While there are benefits to using `import`, this tutorial uses `require()` in order to match [the Express documentation](https://expressjs.com/en/starter/hello-world/). +const server = createServer(app); +server.on("error", (err) => { + throw new Error("Failed to start server", { cause: err }); +}); +server.on("listening", () => { + const address = server.address(); + debug(`Listening on port ${address.port}`); +}); +server.listen(port); +``` -The remainder of the code in this file sets up a node HTTP server with `app` set to a specific port (defined in an environment variable or 3000 if the variable isn't defined), and starts listening and reporting server errors and connections. For now you don't really need to know anything else about the code (everything in this file is "boilerplate"), but feel free to review it if you're interested. +This file imports the "real" application entry point (**app.js**, in the project root), which sets up and exports the [`express()`](https://expressjs.com/en/api/) application object. The rest of the code creates a Node HTTP server for `app` on a specific port (from the `PORT` environment variable, or 3000 if the variable isn't defined), starts listening, logs a message once the server is listening, and throws an error if the server fails to start. For now, you don't really need to know anything else about the code (everything in this file is "boilerplate"), but feel free to review it if you're interested. ### app.js -This file creates an `express` application object (named `app`, by convention), sets up the application with various settings and middleware, and then exports the app from the module. The code below shows just the parts of the file that create and export the app object: - -```js -const express = require("express"); - -const app = express(); -// … -module.exports = app; -``` - -Back in the **www** entry point file above, it is this `module.exports` object that is supplied to the caller when this file is imported. - -Let's work through the **app.js** file in detail. First, we import some useful node libraries into the file using `require()`, including _http-errors_, _express_, _morgan_ and _cookie-parser_ that we previously downloaded for our application using npm; and _path_, which is a core Node library for parsing file and directory paths. +This file creates an `express` application object (named `app`, by convention), sets up the application with various settings and middleware, and then exports the app from the module. First, we import some useful node libraries into the file, including _http-errors_, _express_, and _morgan_. `node:path` is a core Node library for parsing file and directory paths. Then we `import` modules from our routes directory. These modules/files contain code for handling particular sets of related "routes" (URL paths). When we extend the skeleton application, for example to list all books in the library, we will add a new file for dealing with book-related routes. ```js -const createError = require("http-errors"); -const express = require("express"); -const path = require("path"); -const cookieParser = require("cookie-parser"); -const logger = require("morgan"); -``` +import path from "node:path"; +import createError from "http-errors"; +import express from "express"; +import logger from "morgan"; -Then we `require()` modules from our routes directory. These modules/files contain code for handling particular sets of related "routes" (URL paths). When we extend the skeleton application, for example to list all books in the library, we will add a new file for dealing with book-related routes. - -```js -const indexRouter = require("./routes/index"); -const usersRouter = require("./routes/users"); +import indexRouter from "./routes/index.js"; +import usersRouter from "./routes/users.js"; ``` > [!NOTE] > At this point, we have just _imported_ the module; we haven't actually used its routes yet (this happens just a little bit further down the file). -Next, we create the `app` object using our imported _express_ module, and then use it to set up the view (template) engine. There are two parts to setting up the engine. First, we set the `"views"` value to specify the folder where the templates will be stored (in this case the subfolder **/views**). Then we set the `"view engine"` value to specify the template library (in this case "pug"). +Next, we create the `app` object using our imported _express_ module, and then use it to set up the view (template) engine. There are two parts to setting up the engine. First, we set the `"views"` value to specify the folder where the templates will be stored (in this case the subfolder **views/**). Then we set the `"view engine"` value to specify the template library (in this case "pug"). ```js const app = express(); // view engine setup -app.set("views", path.join(__dirname, "views")); +app.set("views", path.join(import.meta.dirname, "views")); app.set("view engine", "pug"); ``` The next set of functions call `app.use()` to add the _middleware_ libraries that we imported above into the request handling chain. -For example, `express.json()` and `express.urlencoded()` are needed to populate [`req.body`](https://expressjs.com/en/api/#req.body) with the form fields. -After these libraries we also use the `express.static` middleware, which makes _Express_ serve all the static files in the **/public** directory in the project root. +For example, `express.urlencoded()` populates [`req.body`](https://expressjs.com/en/5x/api/request/#reqbody) with the fields from submitted HTML forms, and `express.json()` does the same for requests that send JSON. +After these libraries we also use the `express.static` middleware, which makes _Express_ serve all the static files in the **public/** directory in the project root. ```js app.use(logger("dev")); app.use(express.json()); app.use(express.urlencoded({ extended: false })); -app.use(cookieParser()); - -app.use(express.static(path.join(__dirname, "public"))); +app.use(express.static(path.join(import.meta.dirname, "public"))); ``` Now that all the other middleware is set up, we add our (previously imported) route-handling code to the request handling chain. The imported code will define particular routes for the different _parts_ of the site: @@ -514,55 +225,64 @@ app.use((req, res, next) => { // error handler app.use((err, req, res, next) => { - // set locals, only providing error in development + if (res.headersSent) { + next(err); + return; + } + res.locals.message = err.message; res.locals.error = req.app.get("env") === "development" ? err : {}; - - // render the error page - res.status(err.status || 500); + res.status(err.status ?? 500); res.render("error"); }); ``` -The Express application object (app) is now fully configured. The last step is to add it to the module exports (this is what allows it to be imported by **/bin/www**). +The Express application object (app) is now fully configured. The last step is to export it so it can be imported by **server.js**. ```js -module.exports = app; +export default app; ``` ### Routes -The route file **/routes/users.js** is shown below (route files share a similar structure, so we don't need to also show **index.js**). -First, it loads the _express_ module and uses it to get an `express.Router` object. -Then it specifies a route on that object and lastly exports the router from the module (this is what allows the file to be imported into **app.js**). +The route file **routes/index.js** is the most basic route module structure. +First, it imports the `Router` function from the _express_ module and calls it to create a router. +Then it exports the router from the module (this is what allows the file to be imported into **app.js**). We'll add a route to it in [Views (templates)](#views_templates). + +```js +import { Router } from "express"; + +const router = Router(); + +export default router; +``` + +The route file **routes/users.js** is shown below. ```js -const express = require("express"); +import { Router } from "express"; -const router = express.Router(); +const router = Router(); -/* GET users listing. */ -router.get("/", (req, res, next) => { +router.get("/", (req, res) => { res.send("respond with a resource"); }); -module.exports = router; +export default router; ``` +It adds a single route. The route defines a callback that will be invoked whenever an HTTP `GET` request with the correct pattern is detected. The matching pattern is the route specified when the module is imported (`"/users"`) plus whatever is defined in this file (`"/"`). In other words, this route will be used when a URL of `/users/` is received. > [!NOTE] -> Try this out by running the server with node and visiting the URL in your browser: `http://localhost:3000/users/`. You should see a message: 'respond with a resource'. - -One thing of interest above is that the callback function has the third argument `next`, and is hence a middleware function rather than a simple route callback. While the code doesn't currently use the `next` argument, it may be useful in the future if you want to add multiple route handlers to the `'/'` route path. +> Once you've [run the skeleton website](#running_the_skeleton_website), you'll be able to try this out by visiting `http://localhost:3000/users/` in your browser. You should see a message: 'respond with a resource'. ### Views (templates) -The views (templates) are stored in the **/views** directory (as specified in **app.js**) and are given the file extension **.pug**. The method [`Response.render()`](https://expressjs.com/en/5x/api/#res.render) is used to render a specified template along with the values of named variables passed in an object, and then send the result as a response. In the code below from **/routes/index.js** you can see how that route renders a response using the template "index" passing the template variable "title". +The views (templates) are stored in the **views/** directory (as specified in **app.js**) and are given the file extension **.pug**. The method [`Response.render()`](https://expressjs.com/en/5x/api/response/#resrender) is used to render a specified template along with the values of named variables passed in an object, and then send the result as a response. In **routes/index.js**, add the following code above the `export` line, which uses the template "index" passing the template variable "title". ```js -/* GET home page. */ -router.get("/", (req, res, next) => { +router.get("/", (req, res) => { res.render("index", { title: "Express" }); }); ``` @@ -574,12 +294,102 @@ extends layout block content h1= title - p Welcome to #{title} ``` +This template uses `extends layout` to reference the **views/layout.pug** file, which needs to contain the following: + +```pug +doctype html +html(lang='en') + head + title= title + meta(charset='utf-8') + meta(name='viewport', content='width=device-width, initial-scale=1') + link(rel='stylesheet', href='/stylesheets/style.css') + body + div(class='container-fluid') + div(class='row') + div(class='col-sm-10') + block content +``` + +The **views/error.pug** file is rendered by the error handler in **app.js**. It contains the following: + +```pug +extends layout + +block content + h1= message + h2= error.status + pre #{error.stack} +``` + +## Running the skeleton website + +At this point, we have a complete skeleton project. The website doesn't actually _do_ very much yet, but it's worth running it to show that it works. + +1. First, install the dependencies declared in **package.json**. You should already have them installed, but it's good to verify again. + + ```bash + npm install + ``` + +2. Then run the application. + + - On the Windows CMD prompt, use this command: + + ```batch + SET DEBUG=express-locallibrary-tutorial:* & npm start + ``` + + - On Windows PowerShell, use this command: + + ```powershell + $env:DEBUG = "express-locallibrary-tutorial:*"; npm start + ``` + + > [!NOTE] + > PowerShell commands are not provided in the remainder of this tutorial (the listed "Windows" commands assume you're using the Windows CMD prompt). + + - On macOS or Linux, use this command: + + ```bash + DEBUG=express-locallibrary-tutorial:* npm start + ``` + +3. Then load `http://localhost:3000/` in your browser to access the app. + +You should see a browser page that just contains the title "Express". + +Congratulations! You now have a working Express application that can be accessed via port 3000. + +> [!NOTE] +> You could also start the app just using the `npm start` command. Specifying the `DEBUG` variable as shown turns on the debug messages from **server.js**. Other modules may log even without it set, such as the _morgan_ middleware, which logs the `GET` requests in the following output: +> +> ```bash +> DEBUG=express-locallibrary-tutorial:* npm start +> ``` +> +> ```plain +> > express-locallibrary-tutorial@1.0.0 start +> > node server.js +> +> express-locallibrary-tutorial:server Listening on port 3000 +0ms +> GET / 200 78.072 ms - 315 +> GET /stylesheets/style.css 200 1.647 ms - - +> ``` + +To restart the server automatically when you edit JavaScript files, stop it with **Ctrl+C** and use the `devstart` script you added in the development environment tutorial: + +```bash +npm run devstart +``` + +Reload the browser to see your changes. During development, changes to views and stylesheets are served on the next request without restarting the server. + ## Challenge yourself -Create a new route in **/routes/users.js** that will display the text "_You're so cool"_ at URL `/users/cool/`. Test it by running the server and visiting `http://localhost:3000/users/cool/` in your browser +Create a new route in **routes/users.js** that will display the text "_You're so cool_" at URL `/users/cool/`. Test it by running the server and visiting `http://localhost:3000/users/cool/` in your browser. ## Summary @@ -589,7 +399,6 @@ Next, we'll start modifying the skeleton so that it works as a library website. ## See also -- [Express application generator](https://expressjs.com/en/starter/generator/) (Express docs) - [Using template engines with Express](https://expressjs.com/en/guide/using-template-engines/) (Express docs) {{PreviousMenuNext("Learn_web_development/Extensions/Server-side/Express_Nodejs/Tutorial_local_library_website", "Learn_web_development/Extensions/Server-side/Express_Nodejs/mongoose", "Learn_web_development/Extensions/Server-side/Express_Nodejs")}} diff --git a/files/en-us/learn_web_development/extensions/server-side/express_nodejs/tutorial_local_library_website/index.md b/files/en-us/learn_web_development/extensions/server-side/express_nodejs/tutorial_local_library_website/index.md index 5d837ca101da717..c1bf2cc903f4f3b 100644 --- a/files/en-us/learn_web_development/extensions/server-side/express_nodejs/tutorial_local_library_website/index.md +++ b/files/en-us/learn_web_development/extensions/server-side/express_nodejs/tutorial_local_library_website/index.md @@ -35,7 +35,7 @@ Welcome to the MDN "Local Library" Express (Node) tutorial, in which we develop In this series of tutorial articles you will: -- Use the _Express Application Generator_ tool to create a skeleton website and application. +- Create a skeleton website and application. - Start and stop the Node web server. - Use a database to store your application's data. - Create routes for requesting different information, and templates ("views") to render the data as HTML to be displayed in the browser.