mirror of
https://github.com/expressjs/expressjs.com.git
synced 2026-02-22 03:51:33 +00:00
Sue's i18n edits
This commit is contained in:
0
_includes/footer/footer-en.html
Normal file → Executable file
0
_includes/footer/footer-en.html
Normal file → Executable file
4
_includes/header/header-en.html
Normal file → Executable file
4
_includes/header/header-en.html
Normal file → Executable file
@@ -97,10 +97,6 @@
|
||||
</li>
|
||||
<li><a href="{% if page.lang != 'en' %}/{{ page.lang }}{% endif %}/advanced/security-updates.html">Security updates</a>
|
||||
</li>
|
||||
<li><a href="{% if page.lang != 'en' %}/{{ page.lang }}{% endif %}/advanced/best-practice-security.html">Security best practices</a>
|
||||
</li>
|
||||
<li><a href="{% if page.lang != 'en' %}/{{ page.lang }}{% endif %}/advanced/best-practice-performance.html">Performance best practices</a>
|
||||
</li>
|
||||
</ul>
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
2
_includes/notice/notice-en.md
Normal file → Executable file
2
_includes/notice/notice-en.md
Normal file → Executable file
@@ -1 +1 @@
|
||||
This document might be outdated relative to the documentation in English. For the latest updates, please refer the <a href="/">documentation in English</a>.
|
||||
This document might be outdated relative to the documentation in English. For the latest updates, please refer to the <a href="/">documentation in English</a>.
|
||||
|
||||
8
advanced/developing-template-engines.md
Normal file → Executable file
8
advanced/developing-template-engines.md
Normal file → Executable file
@@ -7,9 +7,9 @@ lang: en
|
||||
|
||||
# Developing template engines for Express
|
||||
|
||||
Use the `app.engine(ext, callback)` method to create your own template engine. `ext` refers to the file extension, `callback` is the template engine function which accepts the location of the file, the options object, and the callback function, as its parameters.
|
||||
Use the `app.engine(ext, callback)` method to create your own template engine. `ext` refers to the file extension, and `callback` is the template engine function, which accepts the following items as parameters: the location of the file, the options object, and the callback function.
|
||||
|
||||
The following is an example of implementing a very simple template engine for rendering ".ntl" files.
|
||||
The following code is an example of implementing a very simple template engine for rendering `.ntl` files.
|
||||
|
||||
~~~js
|
||||
var fs = require('fs'); // this engine requires the fs module
|
||||
@@ -26,7 +26,7 @@ app.set('views', './views'); // specify the views directory
|
||||
app.set('view engine', 'ntl'); // register the template engine
|
||||
~~~
|
||||
|
||||
Your app will now be able to render ".ntl" files. Create a file named "index.ntl" in the views directory with the following content.
|
||||
Your app will now be able to render `.ntl` files. Create a file named `index.ntl` in the `views` directory with the following content.
|
||||
|
||||
~~~js
|
||||
#title#
|
||||
@@ -39,4 +39,4 @@ app.get('/', function (req, res) {
|
||||
res.render('index', { title: 'Hey', message: 'Hello there!'});
|
||||
})
|
||||
~~~
|
||||
On making a request to the home page, "index.ntl" will be rendered as HTML.
|
||||
When you make a request to the home page, `index.ntl` will be rendered as HTML.
|
||||
|
||||
46
advanced/pm.md
Normal file → Executable file
46
advanced/pm.md
Normal file → Executable file
@@ -7,7 +7,7 @@ lang: en
|
||||
|
||||
# Process managers for Express apps
|
||||
|
||||
When running Express apps for production, it is helpful to use a _process manager_ to:
|
||||
When you run Express apps for production, it is helpful to use a _process manager_ to achieve the following tasks:
|
||||
|
||||
- Restart the app automatically if it crashes.
|
||||
- Gain insights into runtime performance and resource consumption.
|
||||
@@ -17,31 +17,31 @@ When running Express apps for production, it is helpful to use a _process manage
|
||||
A process manager is somewhat like an application server: it's a "container" for applications that facilitates deployment,
|
||||
provides high availability, and enables you to manage the application at runtime.
|
||||
|
||||
The most popular process managers for Express and other Node applications are:
|
||||
The most popular process managers for Express and other Node.js applications are as follows:
|
||||
|
||||
- [StrongLoop Process Manager](#sl)
|
||||
- [PM2](#pm2)
|
||||
- [Forever](#forever)
|
||||
|
||||
|
||||
Using any of these three tools can be very helpful, however StrongLoop Process Manager is the only solution that provides a comprehensive runtime and deployment solution that address entire Node application life cycle with tooling for every step before and after production in an unified interface.
|
||||
Using any of these three tools can be very helpful, however StrongLoop Process Manager is the only tool that provides a comprehensive runtime and deployment solution that addresses the entire Node.js application life cycle, with tooling for every step before and after production, in a unified interface.
|
||||
|
||||
Here's a brief look at each of these tools.
|
||||
For a detailed comparison, see [http://strong-pm.io/compare/](http://strong-pm.io/compare/).
|
||||
|
||||
## <a id="sl">StrongLoop Process Manager</a>
|
||||
|
||||
StrongLoop Process Manager (StrongLoop PM) is a production process manager for Node.js applications with built-in load balancing, monitoring, multi-host deployment, and a graphical console.
|
||||
It enables you to:
|
||||
StrongLoop Process Manager (StrongLoop PM) is a production process manager for Node.js applications. StrongLoop PM has built-in load balancing, monitoring, and multi-host deployment, and a graphical console.
|
||||
You can use StrongLoop PM for the following tasks:
|
||||
|
||||
- Build, package, and deploy your Node application to a local or remote system.
|
||||
- Build, package, and deploy your Node.js application to a local or remote system.
|
||||
- View CPU profiles and heap snapshots to optimize performance and diagnose memory leaks.
|
||||
- Keep processes and clusters alive forever.
|
||||
- View performance metrics on your application.
|
||||
- Easily manage multi-host deployments with Nginx integration.
|
||||
- Unify multiple StrongLoop PMs to a distributed microservices runtime managed from Arc.
|
||||
- Unify multiple StrongLoop PMs to a distributed microservices runtime that is managed from Arc.
|
||||
|
||||
You can work with StrongLoop PM using a powerful CLI tool, `slc`, or a graphical tool, Arc. It's open source, with professional support provided by StrongLoop.
|
||||
You can work with StrongLoop PM by using a powerful command-line interface tool called `slc`, or a graphical tool called Arc. Arc is open source, with professional support provided by StrongLoop.
|
||||
|
||||
For more information, see [http://strong-pm.io/](http://strong-pm.io/).
|
||||
|
||||
@@ -61,7 +61,7 @@ $ cd my-app
|
||||
$ slc start
|
||||
~~~
|
||||
|
||||
View status of Process Manager and all deployed apps:
|
||||
View the status of Process Manager and all deployed apps:
|
||||
|
||||
~~~sh
|
||||
$ slc ctl
|
||||
@@ -81,7 +81,7 @@ Processes:
|
||||
1.1.57696 57696 4 0.0.0.0:3001
|
||||
~~~
|
||||
|
||||
List all apps (services) under management:
|
||||
List all the apps (services) under management:
|
||||
|
||||
~~~sh
|
||||
$ slc ctl ls
|
||||
@@ -115,7 +115,7 @@ $ slc ctl remove my-app
|
||||
|
||||
## <a id="pm2">PM2</a>
|
||||
|
||||
PM2 is a production process manager for Node.js applications with a built-in load balancer. It allows you to keep applications alive forever, to reload them without downtime and will facilitate common system admin tasks. It also enables you to manage application logging, monitoring, and clustering.
|
||||
PM2 is a production process manager for Node.js applications, that has a built-in load balancer. PM2 allows you to keep applications alive forever and reload them without downtime, and will facilitate common system admin tasks. PM2 also enables you to manage application logging, monitoring, and clustering.
|
||||
|
||||
For more information, see [https://github.com/Unitech/pm2](https://github.com/Unitech/pm2).
|
||||
|
||||
@@ -127,7 +127,7 @@ $ [sudo] npm install pm2 -g
|
||||
|
||||
### Basic use
|
||||
|
||||
Starting an app with `pm2` requires the path of the app to be specified. However, stopping, restarting, and deleting requires just the name or the id of the app.
|
||||
When you start an app by using the `pm2` command, you must specify the path of the app. However, when you stop, restart, or delete an app, you can specify just the name or the id of the app.
|
||||
|
||||
~~~sh
|
||||
$ pm2 start app.js
|
||||
@@ -137,12 +137,12 @@ $ pm2 start app.js
|
||||
├──────────┼────┼──────┼───────┼────────┼─────────┼────────┼─────────────┼──────────┤
|
||||
│ my-app │ 0 │ fork │ 64029 │ online │ 1 │ 0s │ 17.816 MB │ disabled │
|
||||
└──────────┴────┴──────┴───────┴────────┴─────────┴────────┴─────────────┴──────────┘
|
||||
Use `pm2 show <id|name>` to get more details about an app
|
||||
Use the `pm2 show <id|name>` command to get more details about an app.
|
||||
~~~
|
||||
|
||||
Starting an app with `pm2` will immediately send it to the background. You can control the background app from the command line using various `pm2` commands.
|
||||
When you start an app by using the `pm2` command, the app is immediately sent to the background. You can control the background app from the command line by using various `pm2` commands.
|
||||
|
||||
Once an app is started with `pm2` it is registered in `pm2`'s list of processes with an ID, which makes it possible to manage apps with the same name from different directories on the system, using their IDs.
|
||||
After an app is started by using the `pm2` command, it is registered in PM2's list of processes with an ID. You can therefore manage apps with the same name from different directories on the system, by using their IDs.
|
||||
|
||||
Note that if more than one app with the same name is running, `pm2` commands affect all of them. So use IDs instead of names to manage individual apps.
|
||||
|
||||
@@ -170,7 +170,7 @@ To view detailed information about an app:
|
||||
$ pm2 show 0
|
||||
~~~
|
||||
|
||||
To remove an app from `pm2`'s registry:
|
||||
To remove an app from PM2's registry:
|
||||
|
||||
~~~sh
|
||||
$ pm2 delete 0
|
||||
@@ -179,7 +179,7 @@ $ pm2 delete 0
|
||||
|
||||
## <a id="forever">Forever</a>
|
||||
|
||||
Forever is a simple CLI tool for ensuring that a given script runs continuously (forever). Its simple interface makes it ideal for running smaller deployments of Node apps and scripts.
|
||||
Forever is a simple command-line interface tool for ensuring that a given script runs continuously (forever). Forever's simple interface makes it ideal for running smaller deployments of Node.js apps and scripts.
|
||||
|
||||
For more information, see [https://github.com/foreverjs/forever](https://github.com/foreverjs/forever).
|
||||
|
||||
@@ -197,27 +197,27 @@ To start a script, use the `forever start` command and specify the path of the s
|
||||
$ forever start script.js
|
||||
~~~
|
||||
|
||||
This will run the script in daemon mode (in the background).
|
||||
This command will run the script in daemon mode (in the background).
|
||||
|
||||
To run the script attached to the terminal, omit `start`:
|
||||
To run the script so that it is attached to the terminal, omit `start`:
|
||||
|
||||
~~~sh
|
||||
$ forever script.js
|
||||
~~~
|
||||
|
||||
It is a good idea to log output from forever and the script using the logging options `-l`, `-o`, `-e`, as shown this example:
|
||||
It is a good idea to log output from the Forever tool and the script by using the logging options `-l`, `-o`, and `-e`, as shown this example:
|
||||
|
||||
~~~sh
|
||||
$ forever start -l forever.log -o out.log -e err.log script.js
|
||||
~~~
|
||||
|
||||
To view the list of scripts started by forever:
|
||||
To view the list of scripts that were started by Forever:
|
||||
|
||||
~~~sh
|
||||
$ forever list
|
||||
~~~
|
||||
|
||||
To stop a script started by forever use the `forever stop` command and specify the process index (as listed by the `forever list` command).
|
||||
To stop a script that was started by Forever use the `forever stop` command and specify the process index (as listed by the `forever list` command).
|
||||
|
||||
~~~sh
|
||||
$ forever stop 1
|
||||
@@ -229,7 +229,7 @@ Alternatively, specify the path of the file:
|
||||
$ forever stop script.js
|
||||
~~~
|
||||
|
||||
To stop all the scripts started by `forever`:
|
||||
To stop all the scripts that were started by Forever:
|
||||
|
||||
~~~sh
|
||||
$ forever stopall
|
||||
|
||||
18
advanced/security-updates.md
Normal file → Executable file
18
advanced/security-updates.md
Normal file → Executable file
@@ -8,7 +8,7 @@ lang: en
|
||||
# Security updates
|
||||
|
||||
<div class="doc-box doc-notice" markdown="1">
|
||||
Node.js vulnerabilities directly affect Express. Therefore [keep a watch on Node vulnerabilities](http://blog.nodejs.org/vulnerability/) and make sure you are using the latest stable version of Node.
|
||||
Node.js vulnerabilities directly affect Express. Therefore [keep a watch on Node.js vulnerabilities](http://blog.nodejs.org/vulnerability/) and make sure you are using the latest stable version of Node.js.
|
||||
</div>
|
||||
|
||||
The list below enumerates the Express vulnerabilities that were fixed in the specified version update.
|
||||
@@ -16,29 +16,29 @@ The list below enumerates the Express vulnerabilities that were fixed in the spe
|
||||
## 4.x
|
||||
|
||||
* 4.11.1
|
||||
* Fixed root path disclosure vulnerability in express.static, res.sendfile, and res.sendFile
|
||||
* Fixed root path disclosure vulnerability in `express.static`, `res.sendfile`, and `res.sendFile`
|
||||
* 4.10.7
|
||||
* Fixed open redirect vulnerability in express.static ([advisory](https://nodesecurity.io/advisories/serve-static-open-redirect), [CVE-2015-1164](http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2015-1164)).
|
||||
* Fixed open redirect vulnerability in `express.static` ([advisory](https://nodesecurity.io/advisories/serve-static-open-redirect), [CVE-2015-1164](http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2015-1164)).
|
||||
* 4.8.8
|
||||
* Fixed directory traversal vulnerabilities in `express.static` ([advisory](http://nodesecurity.io/advisories/send-directory-traversal) , [CVE-2014-6394](http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2014-6394)).
|
||||
* 4.8.4
|
||||
* Node.js 0.10 can leak `fd`s in certain situations that affect `express.static` and `res.sendfile`. Malicious requests could cause `fd`s to leak and eventually leak to `EMFILE` errors and server unresponsiveness.
|
||||
* Node.js 0.10 can leak `fd`s in certain situations that affect `express.static` and `res.sendfile`. Malicious requests could cause `fd`s to leak and eventually lead to `EMFILE` errors and server unresponsiveness.
|
||||
* 4.8.0
|
||||
* Sparse arrays with extremely high indexes in query string could cause the process to run out of memory and crash the server.
|
||||
* Sparse arrays that have extremely high indexes in the query string could cause the process to run out of memory and crash the server.
|
||||
* Extremely nested query string objects could cause the process to block and make the server unresponsive temporarily.
|
||||
|
||||
## 3.x
|
||||
|
||||
* 3.19.1
|
||||
* Fixed root path disclosure vulnerability in express.static, res.sendfile, and res.sendFile
|
||||
* Fixed root path disclosure vulnerability in `express.static`, `res.sendfile`, and `res.sendFile`
|
||||
* 3.19.0
|
||||
* Fixed open redirect vulnerability in express.static ([advisory](https://nodesecurity.io/advisories/serve-static-open-redirect), [CVE-2015-1164](http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2015-1164)).
|
||||
* Fixed open redirect vulnerability in `express.static` ([advisory](https://nodesecurity.io/advisories/serve-static-open-redirect), [CVE-2015-1164](http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2015-1164)).
|
||||
* 3.16.10
|
||||
* Fixed directory traversal vulnerabilities in `express.static`.
|
||||
* 3.16.6
|
||||
* Node.js 0.10 can leak `fd`s in certain situations that affect `express.static` and `res.sendfile`. Malicious requests could cause `fd`s to leak and eventually leak to `EMFILE` errors and server unresponsiveness.
|
||||
* Node.js 0.10 can leak `fd`s in certain situations that affect `express.static` and `res.sendfile`. Malicious requests could cause `fd`s to leak and eventually lead to `EMFILE` errors and server unresponsiveness.
|
||||
* 3.16.0
|
||||
* Sparse arrays with extremely high indexes in query string could cause the process to run out of memory and crash the server.
|
||||
* Sparse arrays that have extremely high indexes in query string could cause the process to run out of memory and crash the server.
|
||||
* Extremely nested query string objects could cause the process to block and make the server unresponsive temporarily.
|
||||
* 3.3.0
|
||||
* The 404 response of an unsupported method override attempt was susceptible to cross-site scripting attacks.
|
||||
|
||||
12
guide/behind-proxies.md
Normal file → Executable file
12
guide/behind-proxies.md
Normal file → Executable file
@@ -7,10 +7,10 @@ lang: en
|
||||
|
||||
# Express behind proxies
|
||||
|
||||
When running an Express app behind a proxy, set (using [app.set()](/4x/api.html#app.set)) the application variable `trust proxy` to one of the values listed in the following table.
|
||||
When running an Express app behind a proxy, set (by using [app.set()](/4x/api.html#app.set)) the application variable `trust proxy` to one of the values listed in the following table.
|
||||
|
||||
<div class="doc-box doc-info" markdown="1">
|
||||
While the app will not fail to run if the application variable `trust proxy` is not set, it will incorrectly register the proxy's IP address as the client IP address unless `trust proxy` is configured.
|
||||
Although the app will not fail to run if the application variable `trust proxy` is not set, it will incorrectly register the proxy's IP address as the client IP address unless `trust proxy` is configured.
|
||||
</div>
|
||||
|
||||
<table class="doctable" border="1" markdown="1">
|
||||
@@ -27,13 +27,13 @@ If `false`, the app is understood as directly facing the Internet and the client
|
||||
<tr>
|
||||
<td>IP addresses</td>
|
||||
<td markdown="1">
|
||||
An IP address, subnet, or an array of IP addresses, and subnets to trust. The following is the list of pre-configured subnet names.
|
||||
An IP address, subnet, or an array of IP addresses and subnets to trust. The following list shows the pre-configured subnet names:
|
||||
|
||||
* loopback - `127.0.0.1/8`, `::1/128`
|
||||
* linklocal - `169.254.0.0/16`, `fe80::/10`
|
||||
* uniquelocal - `10.0.0.0/8`, `172.16.0.0/12`, `192.168.0.0/16`, `fc00::/7`
|
||||
|
||||
Set IP addresses in any of the following ways:
|
||||
You can set IP addresses in any of the following ways:
|
||||
|
||||
<pre><code class="language-js">app.set('trust proxy', 'loopback') // specify a single subnet
|
||||
app.set('trust proxy', 'loopback, 123.123.123.123') // specify a subnet and an address
|
||||
@@ -67,9 +67,9 @@ Setting a non-`false` `trust proxy` value results in three important changes:
|
||||
<ul>
|
||||
<li markdown="1">The value of [req.hostname](/api.html#req.hostname) is derived from the value set in the `X-Forwarded-Host` header, which can be set by the client or by the proxy.
|
||||
</li>
|
||||
<li markdown="1">`X-Forwarded-Proto` may be set by the reverse proxy to tell the app whether it is https or http or even an invalid name. This value is reflected by [req.protocol](/api.html#req.protocol).
|
||||
<li markdown="1">`X-Forwarded-Proto` can be set by the reverse proxy to tell the app whether it is `https` or `http` or even an invalid name. This value is reflected by [req.protocol](/api.html#req.protocol).
|
||||
</li>
|
||||
<li markdown="1">The [req.ip](/api.html#req.ip) and [req.ips](/api.html#req.ips) values will be populated with `X-Forwarded-For`'s list of addresses.
|
||||
<li markdown="1">The [req.ip](/api.html#req.ip) and [req.ips](/api.html#req.ips) values are populated with the list of addresses from `X-Forwarded-For`.
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@ lang: en
|
||||
|
||||
# Database integration
|
||||
|
||||
Adding database connectivity capability to Express apps is just a matter of loading an appropriate Node.js driver for the database in your app. This document briefly explains how to add and use some of the most popular Node modules for database systems in your Express app:
|
||||
Adding the capability to connect databases to Express apps is just a matter of loading an appropriate Node.js driver for the database in your app. This document briefly explains how to add and use some of the most popular Node.js modules for database systems in your Express app:
|
||||
|
||||
* [Cassandra](#cassandra)
|
||||
* [CouchDB](#couchdb)
|
||||
@@ -167,7 +167,7 @@ MongoClient.connect('mongodb://localhost:27017/animals', function(err, db) {
|
||||
});
|
||||
~~~
|
||||
|
||||
If you want a object model driver for MongoDB, checkout [Mongoose](https://github.com/LearnBoost/mongoose).
|
||||
If you want an object model driver for MongoDB, look at [Mongoose](https://github.com/LearnBoost/mongoose).
|
||||
|
||||
<a name="neo4j"></a>
|
||||
|
||||
|
||||
24
guide/debugging.md
Normal file → Executable file
24
guide/debugging.md
Normal file → Executable file
@@ -8,15 +8,15 @@ lang: en
|
||||
# Debugging Express
|
||||
|
||||
Express uses the [debug](https://github.com/visionmedia/debug) module
|
||||
internally to log information about route matches, middleware in use, application mode,
|
||||
internally to log information about route matches, middleware functions that are in use, application mode,
|
||||
and the flow of the request-response cycle.
|
||||
|
||||
<div class="doc-box doc-info" markdown="1">
|
||||
`debug` is like an augmented version of `console.log`. But unlike `console.log`, you don't have to
|
||||
comment out `debug` logs in production code. It is turned off by default and can be conditionally turned on with the use an environment variable named `DEBUG`.
|
||||
`debug` is like an augmented version of `console.log`, but unlike `console.log`, you don't have to
|
||||
comment out `debug` logs in production code. Logging is turned off by default and can be conditionally turned on by using the `DEBUG` environment variable.
|
||||
</div>
|
||||
|
||||
To see all the internal logs used in Express, simply set the `DEBUG` environment variable to
|
||||
To see all the internal logs used in Express, set the `DEBUG` environment variable to
|
||||
`express:*` when launching your app.
|
||||
|
||||
~~~sh
|
||||
@@ -29,7 +29,7 @@ On Windows, use the corresponding command.
|
||||
> set DEBUG=express:* & node index.js
|
||||
~~~
|
||||
|
||||
Running this on the default app generated by the [express generator](/starter/generator.html) would print the following.
|
||||
Running this command on the default app generated by the [express generator](/starter/generator.html) prints the following output:
|
||||
|
||||
~~~sh
|
||||
$ DEBUG=express:* node ./bin/www
|
||||
@@ -75,7 +75,7 @@ $ DEBUG=express:* node ./bin/www
|
||||
express:router:layer new / +0ms
|
||||
~~~
|
||||
|
||||
Now, when a request is made to the app, you will see the logs specified in the Express code.
|
||||
When a request is then made to the app, you will see the logs specified in the Express code:
|
||||
|
||||
~~~sh
|
||||
express:router dispatching GET / +4h
|
||||
@@ -101,22 +101,16 @@ To see the logs only from the router implementation set the value of `DEBUG` to
|
||||
|
||||
The app generated by the `express` command also uses the `debug` module and its debug namespace is scoped to the name of the application.
|
||||
|
||||
If you generated the app with
|
||||
|
||||
~~~sh
|
||||
$ express sample-app
|
||||
~~~
|
||||
|
||||
You can enable the debug statements with the following command
|
||||
If you generated the app with `$ express sample-app`, you can enable the debug statements with the following command:
|
||||
|
||||
~~~sh
|
||||
$ DEBUG=sample-app node ./bin/www
|
||||
~~~
|
||||
|
||||
You can specify more than one debug namespace by assigning a comma separated list of names, as shown below.
|
||||
You can specify more than one debug namespace by assigning a comma separated list of names:
|
||||
|
||||
~~~sh
|
||||
$ DEBUG=http,mail,express:* node index.js
|
||||
~~~
|
||||
|
||||
For more documentation on `debug`, see the [debug guide](https://github.com/visionmedia/debug).
|
||||
For more documentation about `debug`, see the [debug guide](https://github.com/visionmedia/debug).
|
||||
|
||||
49
guide/error-handling.md
Normal file → Executable file
49
guide/error-handling.md
Normal file → Executable file
@@ -7,8 +7,8 @@ lang: en
|
||||
|
||||
# Error handling
|
||||
|
||||
Define error-handling middleware like other middleware,
|
||||
except with four arguments instead of three, specifically with the signature
|
||||
Define error-handling middleware functions in the same way as other middleware functions,
|
||||
except error-handling functions have four arguments instead of three:
|
||||
`(err, req, res, next)`. For example:
|
||||
|
||||
~~~js
|
||||
@@ -31,14 +31,12 @@ app.use(function(err, req, res, next) {
|
||||
});
|
||||
~~~
|
||||
|
||||
Responses from within the middleware are completely arbitrary. You may
|
||||
wish to respond with an HTML error page, a simple message, a JSON string,
|
||||
or anything else you prefer.
|
||||
Responses from within a middleware function can be in any format that you prefer, such as an HTML error page, a simple message, or a JSON string.
|
||||
|
||||
For organizational (and higher-level framework) purposes, you may define
|
||||
several error-handling middleware, much like you would with
|
||||
regular middleware. For example suppose you wanted to define an error-handler
|
||||
for requests made via XHR, and those without, you might do:
|
||||
For organizational (and higher-level framework) purposes, you can define
|
||||
several error-handling middleware functions, much like you would with
|
||||
regular middleware functions. For example, if you wanted to define an error-handler
|
||||
for requests made by using `XHR`, and those without, you might use the following commands:
|
||||
|
||||
~~~js
|
||||
var bodyParser = require('body-parser');
|
||||
@@ -51,8 +49,8 @@ app.use(clientErrorHandler);
|
||||
app.use(errorHandler);
|
||||
~~~
|
||||
|
||||
Where the more generic `logErrors` may write request and
|
||||
error information to stderr, loggly, or similar services:
|
||||
In this example, the generic `logErrors` might write request and
|
||||
error information to `stderr`, for example:
|
||||
|
||||
~~~js
|
||||
function logErrors(err, req, res, next) {
|
||||
@@ -61,20 +59,19 @@ function logErrors(err, req, res, next) {
|
||||
}
|
||||
~~~
|
||||
|
||||
Where `clientErrorHandler` is defined as the following (note
|
||||
that the error is explicitly passed along to the next):
|
||||
Also in this example, `clientErrorHandler` is defined as follows; in this case, the error is explicitly passed along to the next one:
|
||||
|
||||
~~~js
|
||||
function clientErrorHandler(err, req, res, next) {
|
||||
if (req.xhr) {
|
||||
res.status(500).send({ error: 'Something blew up!' });
|
||||
res.status(500).send({ error: 'Something failed!' });
|
||||
} else {
|
||||
next(err);
|
||||
}
|
||||
}
|
||||
~~~
|
||||
|
||||
The following `errorHandler` "catch-all" implementation may be defined as:
|
||||
The "catch-all" `errorHandler` function might be implemented as follows:
|
||||
|
||||
~~~js
|
||||
function errorHandler(err, req, res, next) {
|
||||
@@ -83,9 +80,9 @@ function errorHandler(err, req, res, next) {
|
||||
}
|
||||
~~~
|
||||
|
||||
If you pass anything to the `next()` function (except the string `'route'`) Express will regard the current request as having errored out and will skip any remaining non-error handling routing/middleware functions. If you want to handle that error in some way you'll have to create an error-handling route as described in the next section.
|
||||
If you pass anything to the `next()` function (except the string `'route'`), Express regards the current request as being in error and will skip any remaining non-error handling routing and middleware functions. If you want to handle that error in some way, you'll have to create an error-handling route as described in the next section.
|
||||
|
||||
If you have a route handler with multiple callback functions you can use the 'route' parameter to skip to the next route handler. For example:
|
||||
If you have a route handler with multiple callback functions you can use the `route` parameter to skip to the next route handler. For example:
|
||||
|
||||
~~~js
|
||||
app.get('/a_route_behind_paywall',
|
||||
@@ -111,24 +108,24 @@ Calls to `next()` and `next(err)` indicate that the current handler is complete
|
||||
|
||||
## The Default Error Handler
|
||||
|
||||
Express comes with an in-built error handler, which takes care of any errors that might be encountered in the app. This default error-handling middleware is added at the end of the middleware stack.
|
||||
Express comes with an in-built error handler, which takes care of any errors that might be encountered in the app. This default error-handling middleware function is added at the end of the middleware function stack.
|
||||
|
||||
If you pass an error to `next()` and you do not handle it in
|
||||
an error handler, it will be handled by the built-in error handler - the error will be written to the client with the
|
||||
an error handler, it will be handled by the built-in error handler; the error will be written to the client with the
|
||||
stack trace. The stack trace is not included in the production environment.
|
||||
|
||||
<div class="doc-box doc-info" markdown="1">
|
||||
Set the environment variable `NODE_ENV` to "production", to run the app in production mode.
|
||||
Set the environment variable `NODE_ENV` to `production`, to run the app in production mode.
|
||||
</div>
|
||||
|
||||
If you call `next()` with an error after you have started writing the
|
||||
response, for instance if you encounter an error while streaming the
|
||||
response to the client, Express' default error handler will close the
|
||||
connection and make the request be considered failed.
|
||||
response (for example, if you encounter an error while streaming the
|
||||
response to the client) the Express default error handler closes the
|
||||
connection and fails the request.
|
||||
|
||||
So when you add a custom error handler you will want to delegate to
|
||||
the default error handling mechanisms in express, when the headers
|
||||
have already been sent to the client.
|
||||
So when you add a custom error handler, you will want to delegate to
|
||||
the default error handling mechanisms in Express, when the headers
|
||||
have already been sent to the client:
|
||||
|
||||
~~~js
|
||||
function errorHandler(err, req, res, next) {
|
||||
|
||||
111
guide/migrating-4.md
Normal file → Executable file
111
guide/migrating-4.md
Normal file → Executable file
@@ -9,7 +9,7 @@ lang: en
|
||||
|
||||
<h2 id="overview">Overview</h2>
|
||||
|
||||
Express 4 is a breaking change from Express 3. That means an existing Express 3 app will not work if you update the Express version in its dependencies.
|
||||
Express 4 is a breaking change from Express 3, so. That means an existing Express 3 app will not work if you update the Express version in its dependencies.
|
||||
|
||||
This article covers:
|
||||
|
||||
@@ -21,10 +21,10 @@ This article covers:
|
||||
|
||||
<h2 id="changes">Changes in Express 4</h2>
|
||||
|
||||
The main changes in Express 4 are:
|
||||
There are several significant changes in Express 4:
|
||||
|
||||
<ul class="doclist">
|
||||
<li><a href="#core-changes">Changes to Express core and middleware system: </a>The dependency on Connect and built-in middleware were removed, so you must add middleware yourself.
|
||||
<li><a href="#core-changes">Changes to Express core and middleware system.</a> The dependencies on Connect and built-in middleware were removed, so you must add middleware yourself.
|
||||
</li>
|
||||
<li><a href="#routing">Changes to the routing system.</a></li>
|
||||
<li><a href="#other-changes">Various other changes.</a></li>
|
||||
@@ -40,12 +40,12 @@ Changes to Express core and middleware system
|
||||
</h3>
|
||||
|
||||
Express 4 no longer depends on Connect, and removes all built-in
|
||||
middleware from its core, except `express.static`. This means
|
||||
middleware from its core, except for the `express.static` function. This means that
|
||||
Express is now an independent routing and middleware web framework, and
|
||||
Express versioning and releases are not affected by middleware updates.
|
||||
|
||||
With the built-in middleware gone, you must explicitly add all the
|
||||
middleware required to run your app. Simply follow these steps:
|
||||
Without built-in middleware, you must explicitly add all the
|
||||
middleware that is required to run your app. Simply follow these steps:
|
||||
|
||||
1. Install the module: `npm install --save <module-name>`
|
||||
2. In your app, require the module: `require('module-name')`
|
||||
@@ -96,8 +96,7 @@ GitHub.
|
||||
|
||||
<h4 id="app-use"><code>app.use</code> accepts parameters</h4>
|
||||
|
||||
In version 4 you can now load middleware on a path with a variable
|
||||
parameter and read the parameter value from the route handler.
|
||||
In version 4 you can use a variable parameter to define the path where middleware functions are loaded, then read the value of the parameter from the route handler.
|
||||
For example:
|
||||
|
||||
~~~js
|
||||
@@ -124,11 +123,10 @@ new features to help organize your routes:
|
||||
<h4 id="app-route"><code>app.route()</code> method</h4>
|
||||
|
||||
The new `app.route()` method enables you to create chainable route handlers
|
||||
for a route path. Since the path is specified in a single location, it
|
||||
helps to create modular routes and reduce redundancy and typos. For more
|
||||
information on routes, see [`Router()` documentation](/4x/api.html#router).
|
||||
for a route path. Because the path is specified in a single location, creating modular routes is helpful, as is reducing redundancy and typos. For more
|
||||
information about routes, see [`Router()` documentation](/4x/api.html#router).
|
||||
|
||||
Here is an example of chained route handlers defined using `app.route()`.
|
||||
Here is an example of chained route handlers that are defined by using the `app.route()` function.
|
||||
|
||||
~~~js
|
||||
app.route('/book')
|
||||
@@ -145,15 +143,15 @@ app.route('/book')
|
||||
|
||||
<h4 id="express-router"><code>express.Router</code> class</h4>
|
||||
|
||||
The other feature to help organize routes is a new class,
|
||||
The other feature that helps to organize routes is a new class,
|
||||
`express.Router`, that you can use to create modular mountable
|
||||
route handlers. A `Router` instance is a complete middleware and
|
||||
routing system; for this reason it is often referred to as a "mini-app".
|
||||
|
||||
The following example creates a router as a module, loads a middleware in
|
||||
The following example creates a router as a module, loads middleware in
|
||||
it, defines some routes, and mounts it on a path on the main app.
|
||||
|
||||
Create a router file named `birds.js` in the app directory,
|
||||
For example, create a router file named `birds.js` in the app directory,
|
||||
with the following content:
|
||||
|
||||
~~~js
|
||||
@@ -185,15 +183,15 @@ var birds = require('./birds');
|
||||
app.use('/birds', birds);
|
||||
~~~
|
||||
|
||||
The app will now be able to handle requests to `/birds` and
|
||||
`/birds/about`, along with calling the `timeLog`
|
||||
middleware specific to the route.
|
||||
The app will now be able to handle requests to the `/birds` and
|
||||
`/birds/about` paths, and will call the `timeLog`
|
||||
middleware that is specific to the route.
|
||||
|
||||
<h3 id="other-changes">
|
||||
Other changes
|
||||
</h3>
|
||||
|
||||
The following table lists other small but important changes in Express 4.
|
||||
The following table lists other small but important changes in Express 4:
|
||||
|
||||
<table class="doctable" border="1">
|
||||
<tr>
|
||||
@@ -201,17 +199,17 @@ The following table lists other small but important changes in Express 4.
|
||||
<th>Description</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Node</td>
|
||||
<td>Express 4 requires Node 0.10.x or later and has dropped support for
|
||||
Node 0.8.x.</td>
|
||||
<td>Node.js</td>
|
||||
<td>Express 4 requires Node.js 0.10.x or later and has dropped support for
|
||||
Node.js 0.8.x.</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td markdown="1">
|
||||
`http.createServer()`
|
||||
</td>
|
||||
<td markdown="1">
|
||||
The `http` module is no longer needed, unless you need to directly work with it (socket.io/SPDY/HTTPS). The app can be started using
|
||||
`app.listen()`.
|
||||
The `http` module is no longer needed, unless you need to directly work with it (socket.io/SPDY/HTTPS). The app can be started by using the
|
||||
`app.listen()` function.
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
@@ -219,9 +217,9 @@ The `http` module is no longer needed, unless you need to directly work with it
|
||||
`app.configure()`
|
||||
</td>
|
||||
<td markdown="1">
|
||||
`app.configure()` has been removed. Use
|
||||
The `app.configure()` function has been removed. Use the
|
||||
`process.env.NODE_ENV` or
|
||||
`app.get('env')` to detect the environment and configure the app accordingly.
|
||||
`app.get('env')` function to detect the environment and configure the app accordingly.
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
@@ -389,18 +387,18 @@ $ npm install serve-favicon morgan method-override express-session body-parser m
|
||||
|
||||
Make the following changes to `app.js`:
|
||||
|
||||
1. The built-in Express middleware `express.favicon`,
|
||||
1. The built-in Express middleware functions `express.favicon`,
|
||||
`express.logger`, `express.methodOverride`,
|
||||
`express.session`, `express.bodyParser` and
|
||||
`express.errorHandler` are no longer available on the
|
||||
`express` object. You must install their alternatives
|
||||
manually and load them in the app.
|
||||
|
||||
2. You no longer need to load `app.router`.
|
||||
It is not a valid Express 4 app object, so remove
|
||||
`app.use(app.router);`
|
||||
2. You no longer need to load the `app.router` function.
|
||||
It is not a valid Express 4 app object, so remove the
|
||||
`app.use(app.router);` code.
|
||||
|
||||
3. Make sure the middleware are loaded in the right order - load `errorHandler` after loading the app routes.
|
||||
3. Make sure that the middleware functions are loaded in the correct order - load `errorHandler` after loading the app routes.
|
||||
|
||||
<h3 id="">Version 4 app</h3>
|
||||
|
||||
@@ -433,7 +431,7 @@ Running the above `npm` command will update `package.json` as follows:
|
||||
<h4 id=""><code>app.js</code></h4>
|
||||
|
||||
Then, remove invalid code, load the required middleware, and make other
|
||||
changes as necessary. Then `app.js` will look like this:
|
||||
changes as necessary. The `app.js` file will look like this:
|
||||
|
||||
~~~js
|
||||
var http = require('http');
|
||||
@@ -482,7 +480,7 @@ server.listen(app.get('port'), function(){
|
||||
~~~
|
||||
|
||||
<div class="doc-box doc-info" markdown="1">
|
||||
Unless you need to work directly with the `http` module (socket.io/SPDY/HTTPS), loading it is not required, and the app can be simple started this way:
|
||||
Unless you need to work directly with the `http` module (socket.io/SPDY/HTTPS), loading it is not required, and the app can be simply started this way:
|
||||
<pre><code class="language-js">app.listen(app.get('port'), function(){
|
||||
console.log('Express server listening on port ' + app.get('port'));
|
||||
});</code></pre>
|
||||
@@ -490,8 +488,8 @@ Unless you need to work directly with the `http` module (socket.io/SPDY/HTTPS),
|
||||
|
||||
<h3 id="">Run the app</h3>
|
||||
|
||||
With that, the migration process is complete, and the app is now an
|
||||
Express 4 app. To confirm, start the app with the following command:
|
||||
The migration process is complete, and the app is now an
|
||||
Express 4 app. To confirm, start the app by using the following command:
|
||||
|
||||
~~~sh
|
||||
$ node .
|
||||
@@ -510,13 +508,13 @@ The command-line tool to generate an Express app is still
|
||||
<h3 id="">Installing </h3>
|
||||
|
||||
If you already have the Express 3 app generator installed on your system,
|
||||
you must uninstall it as follows:
|
||||
you must uninstall it:
|
||||
|
||||
~~~sh
|
||||
$ npm uninstall -g express
|
||||
~~~
|
||||
Depending on how your file and directory privileges are configured,
|
||||
you may need to run this command with `sudo`.
|
||||
you might need to run this command with `sudo`.
|
||||
|
||||
Now install the new generator:
|
||||
|
||||
@@ -525,7 +523,7 @@ $ npm install -g express-generator
|
||||
~~~
|
||||
|
||||
Depending on how your file and directory privileges are configured,
|
||||
you may need to run this command with `sudo`.
|
||||
you might need to run this command with `sudo`.
|
||||
|
||||
Now the `express` command on your system is updated to the
|
||||
Express 4 generator.
|
||||
@@ -547,39 +545,38 @@ Execute the following command to create an Express 4 app:
|
||||
$ express app4
|
||||
~~~
|
||||
|
||||
If you look at the contents of `app4/app.js`, you will notice
|
||||
that all the middleware (except `express.static`) required for
|
||||
the app are loaded as independent modules and the `router` middleware
|
||||
If you look at the contents of the `app4/app.js` file, you will notice
|
||||
that all the middleware functions (except `express.static`) that are required for
|
||||
the app are loaded as independent modules, and the `router` middleware
|
||||
is no longer explicitly loaded in the app.
|
||||
|
||||
You will also notice that the `app.js` file is now a Node module,
|
||||
compared to the standalone app generated by the old generator.
|
||||
You will also notice that the `app.js` file is now a Node.js module, in contrast to the standalone app that was generated by the old generator.
|
||||
|
||||
After installing the dependencies, start the app using the following command:
|
||||
After installing the dependencies, start the app by using the following command:
|
||||
|
||||
~~~sh
|
||||
$ npm start
|
||||
~~~
|
||||
|
||||
If you peek at the npm start script in `package.json` file,
|
||||
If you look at the npm start script in the `package.json` file,
|
||||
you will notice that the actual command that starts the app is
|
||||
`node ./bin/www`, which used to be `node app.js`
|
||||
in Express 3.
|
||||
|
||||
Since the `app.js` file generated by the Express 4 generator
|
||||
is now a Node module, it can no longer be started independently as an app
|
||||
(unless you modify the code). It has to be to be loaded in a Node file
|
||||
and started via the Node file. The Node file is `./bin/www`
|
||||
Because the `app.js` file that was generated by the Express 4 generator
|
||||
is now a Node.js module, it can no longer be started independently as an app
|
||||
(unless you modify the code). The module must be loaded in a Node.js file
|
||||
and started via the Node.js file. The Node.js file is `./bin/www`
|
||||
in this case.
|
||||
|
||||
Neither the `bin` directory nor the extensionless `www`
|
||||
file is mandatory for creating an Express app or starting the app. They are
|
||||
just suggestions by the generator, so feel free to modify them to suit your
|
||||
just suggestions made by the generator, so feel free to modify them to suit your
|
||||
needs.
|
||||
|
||||
To get rid of the `www` directory and keep things the "Express 3 way",
|
||||
delete the line that says `module.exports = app;` at the end of
|
||||
`app.js`, and paste the following code in its place.
|
||||
delete the line that says `module.exports = app;` at the end of the
|
||||
`app.js` file, then paste the following code in its place:
|
||||
|
||||
~~~js
|
||||
app.set('port', process.env.PORT || 3000);
|
||||
@@ -589,7 +586,7 @@ var server = app.listen(app.get('port'), function() {
|
||||
});
|
||||
~~~
|
||||
|
||||
Make sure to load the `debug` module at the top of `app.js` with the following code.
|
||||
Ensure that you load the `debug` module at the top of the `app.js` file by using the following code:
|
||||
|
||||
~~~js
|
||||
var debug = require('debug')('app4');
|
||||
@@ -597,7 +594,7 @@ var debug = require('debug')('app4');
|
||||
|
||||
Next, change `"start": "node ./bin/www"` in the `package.json` file to `"start": "node app.js"`.
|
||||
|
||||
With that, you just moved the functionality of `./bin/www` back to
|
||||
`app.js`. Not that it is recommended, but the exercise helps
|
||||
to understand how `./bin/www` works, and why `app.js`
|
||||
won't start on its own anymore.
|
||||
You have now moved the functionality of `./bin/www` back to
|
||||
`app.js`. This change is not recommended, but the exercise helps you
|
||||
to understand how the `./bin/www` file works, and why the `app.js` file
|
||||
no longer starts on its own.
|
||||
|
||||
38
guide/migrating-5.md
Normal file → Executable file
38
guide/migrating-5.md
Normal file → Executable file
@@ -9,21 +9,21 @@ lang: en
|
||||
|
||||
<h2 id="overview">Overview</h2>
|
||||
|
||||
Express 5.0 is still in the alpha release stage, but here is preview of the changes that will be in the release and how to migrate your Express 4 app to Express 5.
|
||||
Express 5.0 is still in the alpha release stage, but here is a preview of the changes that will be in the release and how to migrate your Express 4 app to Express 5.
|
||||
|
||||
Express 5 is not very different from Express 4: The changes to the API are not as significant as from 3.0 to 4.0. Although the basic API remains the same, there are still breaking changes; in other words an existing Express 4 program may not work if you update it to use Express 5.
|
||||
Express 5 is not very different from Express 4: The changes to the API are not as significant as from 3.0 to 4.0. Although the basic API remains the same, there are still breaking changes; in other words an existing Express 4 program might not work if you update it to use Express 5.
|
||||
|
||||
To install the latest alpha and preview Express 5, enter this command in your application root directory:
|
||||
To install the latest alpha and to preview Express 5, enter the following command in your application root directory:
|
||||
|
||||
~~~sh
|
||||
$ npm install express@5.0.0-alpha.2 --save
|
||||
~~~
|
||||
|
||||
After you do this, run your automated tests to see what fails, and fix them according to the updates listed below. After addressing test failures, run your app to see what errors occur. You'll find out right away if the app uses any methods or properties that are not supported.
|
||||
You can then run your automated tests to see what fails, and fix problems according to the updates listed below. After addressing test failures, run your app to see what errors occur. You'll find out right away if the app uses any methods or properties that are not supported.
|
||||
|
||||
<h2 id="changes">Changes in Express 5</h2>
|
||||
|
||||
Following is the list of changes (as of the alpha 2 release ) that will affect you as a user of Express.
|
||||
Here is the list of changes (as of the alpha 2 release ) that will affect you as a user of Express.
|
||||
See the [pull request](https://github.com/strongloop/express/pull/2237) for a list of all the planned features.
|
||||
|
||||
**Removed methods and properties**
|
||||
@@ -57,17 +57,17 @@ See the [pull request](https://github.com/strongloop/express/pull/2237) for a li
|
||||
|
||||
<h3>Removed methods and properties</h3>
|
||||
|
||||
If you use any of these methods or properties in your app, it will crash. So, you'll need to go through and change your app once you update to version 5.
|
||||
If you use any of these methods or properties in your app, it will crash. So, you'll need to change your app after you update to version 5.
|
||||
|
||||
<h4 id="app.del">app.del()</h4>
|
||||
|
||||
Express 5 no longer supports `app.del()`. Using it will throw an error. For registering HTTP DELETE routes, use `app.delete()` instead.
|
||||
Express 5 no longer supports the `app.del()` function. If you use this function an error is thrown. For registering HTTP DELETE routes, use the `app.delete()` function instead.
|
||||
|
||||
Initially `del` was used instead of `delete` considering delete is a reserved keyword in JavaScript. However, as of ECMAScript 6, `delete` and other reserved keywords can legally be used as a property names. You can read the discussion which lead to the deprecation of `app.del` here.
|
||||
Initially `del` was used instead of `delete`, because `delete` is a reserved keyword in JavaScript. However, as of ECMAScript 6, `delete` and other reserved keywords can legally be used as property names. You can read the discussion that led to the deprecation of the `app.del` function here.
|
||||
|
||||
<h4 id="app.param">app.param(fn)</h4>
|
||||
|
||||
The `app.param(fn)` signature was used for modifying the behavior of `app.param(name, fn)`. It has been deprecated since v4.11.0, and Express 5 no longer supports it at all.
|
||||
The `app.param(fn)` signature was used for modifying the behavior of the `app.param(name, fn)` function. It has been deprecated since v4.11.0, and Express 5 no longer supports it at all.
|
||||
|
||||
<h4 id="plural">Pluralized method names</h4>
|
||||
|
||||
@@ -79,15 +79,15 @@ The following method names have been pluralized. In Express 4, using the old met
|
||||
|
||||
`req.acceptsLanguage()` is replaced by `req.acceptsLanguages()`.
|
||||
|
||||
<h4 id="leading">Leading colon (:) in name for app.param(name, fn)</h4>
|
||||
<h4 id="leading">Leading colon (:) in the name for app.param(name, fn)</h4>
|
||||
|
||||
A leading colon character (:) in name for `app.param(name, fn)` is remnant of Express 3, and for the sake of backwards compatibility, Express 4 supported it with a deprecation notice. Express 5 will silently ignore it; use the name parameter without prefixing it with a colon.
|
||||
A leading colon character (:) in the name for the `app.param(name, fn)` function is a remnant of Express 3, and for the sake of backwards compatibility, Express 4 supported it with a deprecation notice. Express 5 will silently ignore it and use the name parameter without prefixing it with a colon.
|
||||
|
||||
This should not affect your code if you follow the Express 4 documentation of [app.param](/4x/api.html#app.param), as it makes no mention of the leading colon.
|
||||
|
||||
<h4 id="req.param">req.param(name)</h4>
|
||||
|
||||
This potentially confusing and dangerous method of retrieving form data has been removed. You will now need to specifically look for the submitted parameter name in `req.params`, `req.body`, or `req.query`.
|
||||
This potentially confusing and dangerous method of retrieving form data has been removed. You will now need to specifically look for the submitted parameter name in the `req.params`, `req.body`, or `req.query` object.
|
||||
|
||||
<h4 id="res.json">res.json(obj, status)</h4>
|
||||
|
||||
@@ -103,29 +103,29 @@ Express 5 no longer supports the signature `res.send(obj, status)`. Instead, set
|
||||
|
||||
<h4 id="res.send.status">res.send(status)</h4>
|
||||
|
||||
Express 5 no longer supports the signature <code>res.send(<em>status</em>)</code>, where _`status`_ is a number. Instead, use `res.sendStatus(statusCode)`, which sets the HTTP response header status code and sends the text version of the code: "Not Found", "Internal Server Error", and so on.
|
||||
If you need to send a number using `res.send()`, quote the number to convert it to a string, so that Express does not interpret it as an attempt at using the unsupported old signature.
|
||||
Express 5 no longer supports the signature <code>res.send(<em>status</em>)</code>, where _`status`_ is a number. Instead, use the `res.sendStatus(statusCode)` function, which sets the HTTP response header status code and sends the text version of the code: "Not Found", "Internal Server Error", and so on.
|
||||
If you need to send a number by using the `res.send()` function, quote the number to convert it to a string, so that Express does not interpret it as an attempt to use the unsupported old signature.
|
||||
|
||||
<h4 id="res.sendfile">res.sendfile()</h4>
|
||||
|
||||
`res.sendfile()` has been replaced by a camel-cased version `res.sendFile()` in Express 5.
|
||||
The `res.sendfile()` function has been replaced by a camel-cased version `res.sendFile()` in Express 5.
|
||||
|
||||
<h3>Changed</h3>
|
||||
|
||||
<h4 id="app.router">app.router</h4>
|
||||
|
||||
The `app.router` object, which was removed in Express 4, has made a comeback in Express 5. In the new version, it is a just a reference to the base Express router, unlike in Express 3, where an app had to explicitly load it.
|
||||
The `app.router` object, which was removed in Express 4, has made a comeback in Express 5. In the new version, this object is a just a reference to the base Express router, unlike in Express 3, where an app had to explicitly load it.
|
||||
|
||||
<h4 id="req.host">req.host</h4>
|
||||
|
||||
In Express 4, `req.host` incorrectly stripped off the port number if it was present. In Express 5 the port number is maintained.
|
||||
In Express 4, the `req.host` function incorrectly stripped off the port number if it was present. In Express 5 the port number is maintained.
|
||||
|
||||
<h4 id="req.query">req.query</h4>
|
||||
|
||||
In Express 4.7 and Express 5 onwards, the query parser option can accept false to disable query string parsing, when you want to use your own function for query string parsing logic.
|
||||
In Express 4.7 and Express 5 onwards, the query parser option can accept `false` to disable query string parsing when you want to use your own function for query string parsing logic.
|
||||
|
||||
<h3>Improvements</h3>
|
||||
|
||||
<h4 id="res.render">res.render()</h4>
|
||||
|
||||
This method now enforces asynchronous behavior for all view engines, avoiding bugs caused by view engines which had a synchronous implementation and violated the recommended interface.
|
||||
This method now enforces asynchronous behavior for all view engines, avoiding bugs caused by view engines that had a synchronous implementation and that violated the recommended interface.
|
||||
|
||||
73
guide/routing.md
Normal file → Executable file
73
guide/routing.md
Normal file → Executable file
@@ -7,11 +7,11 @@ lang: en
|
||||
|
||||
# Routing
|
||||
|
||||
Routing refers to the definition of end points (URIs) to an application and how it responds to client requests.
|
||||
Routing refers to the definition of application end points (URIs) and how they respond to client requests.
|
||||
|
||||
A route is a combination of a URI, a HTTP request method (GET, POST, and so on), and one or more handlers for the endpoint. It takes the following structure `app.METHOD(path, [callback...], callback)`, where `app` is an instance of `express`, `METHOD` is an [HTTP request method](http://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol), `path` is a path on the server, and `callback` is the function executed when the route is matched.
|
||||
A route is a combination of a URI, an HTTP request method (such as GET and POST), and one or more handlers for the endpoint. Routes use the following structure: `app.METHOD(path, [callback...], callback)`, where `app` is an instance of `express`, `METHOD` is an [HTTP request method](http://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol), `path` is a path on the server, and `callback` is the function that is executed when the route is matched.
|
||||
|
||||
The following is an example of a very basic route.
|
||||
The following code is an example of a very basic route.
|
||||
|
||||
~~~js
|
||||
var express = require('express');
|
||||
@@ -25,9 +25,9 @@ app.get('/', function(req, res) {
|
||||
|
||||
<h2 id="route-methods">Route methods</h2>
|
||||
|
||||
A route method is derived from one of the HTTP methods, and is attached to an instance of `express`.
|
||||
A route method is derived from one of the HTTP methods, and is attached to an instance of the `express` class.
|
||||
|
||||
The following is an example of routes defined for the GET and the POST methods to the root of the app.
|
||||
The following code is an example of routes that are defined for the GET and the POST methods to the root of the app.
|
||||
|
||||
~~~js
|
||||
// GET method route
|
||||
@@ -42,16 +42,16 @@ app.post('/', function (req, res) {
|
||||
|
||||
~~~
|
||||
|
||||
Express supports the following routing methods corresponding to HTTP methods: `get`, `post`, `put`, `head`, `delete`, `options`, `trace`, `copy`, `lock`, `mkcol`, `move`, `purge`, `propfind`, `proppatch`, `unlock`, `report`, `mkactivity`, `checkout`, `merge`, `m-search`, `notify`, `subscribe`, `unsubscribe`, `patch`, `search`, and `connect`.
|
||||
Express supports the following routing methods that correspond to HTTP methods: `get`, `post`, `put`, `head`, `delete`, `options`, `trace`, `copy`, `lock`, `mkcol`, `move`, `purge`, `propfind`, `proppatch`, `unlock`, `report`, `mkactivity`, `checkout`, `merge`, `m-search`, `notify`, `subscribe`, `unsubscribe`, `patch`, `search`, and `connect`.
|
||||
|
||||
<div class="doc-box doc-info" markdown="1">
|
||||
To route methods which translate to invalid JavaScript variable names, use the bracket notation. For example,
|
||||
To route methods that translate to invalid JavaScript variable names, use the bracket notation. For example,
|
||||
`app['m-search']('/', function ...`
|
||||
</div>
|
||||
|
||||
There is a special routing method, `app.all()`, which is not derived from any HTTP method. It is used for loading middleware at a path for all request methods.
|
||||
There is a special routing method, `app.all()`, which is not derived from any HTTP method. This method is used for loading middleware functions at a path for all request methods.
|
||||
|
||||
In the following example, the handler will be executed for requests to "/secret" whether using GET, POST, PUT, DELETE, or any other HTTP request method supported in the [http module](https://nodejs.org/api/http.html#http_http_methods).
|
||||
In the following example, the handler will be executed for requests to "/secret" whether you are using GET, POST, PUT, DELETE, or any other HTTP request method that is supported in the [http module](https://nodejs.org/api/http.html#http_http_methods).
|
||||
|
||||
~~~js
|
||||
app.all('/secret', function (req, res, next) {
|
||||
@@ -62,20 +62,20 @@ app.all('/secret', function (req, res, next) {
|
||||
|
||||
<h2 id="route-paths">Route paths</h2>
|
||||
|
||||
Route paths, in combination with a request method, define the endpoints at which requests can be made to. They can be strings, string patterns, or regular expressions.
|
||||
Route paths, in combination with a request method, define the endpoints at which requests can be made. Route paths can be strings, string patterns, or regular expressions.
|
||||
|
||||
<div class="doc-box doc-info" markdown="1">
|
||||
Express uses [path-to-regexp](https://www.npmjs.com/package/path-to-regexp) for matching the route paths; see its documentation for all the possibilities in defining route paths. [Express Route Tester](http://forbeslindesay.github.io/express-route-tester/) is a handy tool for testing basic Express routes, although it does not support pattern matching.
|
||||
Express uses [path-to-regexp](https://www.npmjs.com/package/path-to-regexp) for matching the route paths; see the path-to-regexp documentation for all the possibilities in defining route paths. [Express Route Tester](http://forbeslindesay.github.io/express-route-tester/) is a handy tool for testing basic Express routes, although it does not support pattern matching.
|
||||
</div>
|
||||
|
||||
<div class="doc-box doc-warn" markdown="1">
|
||||
Query strings are not a part of the route path.
|
||||
Query strings are not part of the route path.
|
||||
</div>
|
||||
|
||||
Examples of route paths based on strings:
|
||||
Examples of route paths that are based on strings:
|
||||
|
||||
~~~js
|
||||
// will match request to the root
|
||||
// will match a request to the root
|
||||
app.get('/', function (req, res) {
|
||||
res.send('root');
|
||||
});
|
||||
@@ -116,18 +116,18 @@ app.get('/ab(cd)?e', function(req, res) {
|
||||
~~~
|
||||
|
||||
<div class="doc-box doc-info" markdown="1">
|
||||
The characters ?, +, *, and () are subsets of their Regular Expression counterparts. The hyphen (-) and the dot (.) are interpreted literally by string-based paths.
|
||||
The characters ?, +, *, and () are subsets of their regular expression counterparts. The hyphen (-) and the dot (.) are interpreted literally by string-based paths.
|
||||
</div>
|
||||
|
||||
Examples of route paths based on regular expressions:
|
||||
|
||||
~~~js
|
||||
// will match anything with an a in the route name:
|
||||
// will match anything with an "a" in the route name:
|
||||
app.get(/a/, function(req, res) {
|
||||
res.send('/a/');
|
||||
});
|
||||
|
||||
// will match butterfly, dragonfly; but not butterflyman, dragonfly man, and so on
|
||||
// will match butterfly and dragonfly; but not butterflyman, dragonfly man, and so on
|
||||
app.get(/.*fly$/, function(req, res) {
|
||||
res.send('/.*fly$/');
|
||||
});
|
||||
@@ -135,9 +135,9 @@ app.get(/.*fly$/, function(req, res) {
|
||||
|
||||
<h2 id="route-handlers">Route handlers</h2>
|
||||
|
||||
You can provide multiple callback functions that behave just like [middleware](/guide/using-middleware.html) to handle a request. The only exception is that these callbacks may invoke `next('route')` to bypass the remaining route callback(s). You can use this mechanism to impose pre-conditions on a route, then pass control to subsequent routes if there's no reason to proceed with the current route.
|
||||
You can provide multiple callback functions that behave like [middleware](/guide/using-middleware.html) to handle a request. The only exception is that these callbacks might invoke `next('route')` to bypass the remaining route callbacks. You can use this mechanism to impose pre-conditions on a route, then pass control to subsequent routes if there's no reason to proceed with the current route.
|
||||
|
||||
Route handlers can come in the form of a function, an array of functions, or various combinations of both, as shown the following examples.
|
||||
Route handlers can be in the form of a function, an array of functions, or combinations of both, as shown in the following examples.
|
||||
|
||||
A route can be handled using a single callback function:
|
||||
|
||||
@@ -147,11 +147,11 @@ app.get('/example/a', function (req, res) {
|
||||
});
|
||||
~~~
|
||||
|
||||
A route can be handled using a more than one callback function (make sure to specify the `next` object):
|
||||
A route can be handled using more than one callback function (make sure you specify the `next` object):
|
||||
|
||||
~~~js
|
||||
app.get('/example/b', function (req, res, next) {
|
||||
console.log('response will be sent by the next function ...');
|
||||
console.log('the response will be sent by the next function ...');
|
||||
next();
|
||||
}, function (req, res) {
|
||||
res.send('Hello from B!');
|
||||
@@ -178,7 +178,7 @@ var cb2 = function (req, res) {
|
||||
app.get('/example/c', [cb0, cb1, cb2]);
|
||||
~~~
|
||||
|
||||
A route can be handled using a combination of array of functions and independent functions:
|
||||
A route can be handled using a combination of independent functions and arrays of functions:
|
||||
|
||||
~~~js
|
||||
var cb0 = function (req, res, next) {
|
||||
@@ -192,7 +192,7 @@ var cb1 = function (req, res, next) {
|
||||
}
|
||||
|
||||
app.get('/example/d', [cb0, cb1], function (req, res, next) {
|
||||
console.log('response will be sent by the next function ...');
|
||||
console.log('the response will be sent by the next function ...');
|
||||
next();
|
||||
}, function (req, res) {
|
||||
res.send('Hello from D!');
|
||||
@@ -201,7 +201,7 @@ app.get('/example/d', [cb0, cb1], function (req, res, next) {
|
||||
|
||||
<h2 id="response-methods">Response methods</h2>
|
||||
|
||||
The methods on the response object (`res`) in the following table can send a response to the client and terminate the request response cycle. If none of them is called from a route handler, the client request will be left hanging.
|
||||
The methods on the response object (`res`) in the following table can send a response to the client, and terminate the request-response cycle. If none of these methods are called from a route handler, the client request will be left hanging.
|
||||
|
||||
| Method | Description
|
||||
|----------------------|--------------------------------------
|
||||
@@ -217,12 +217,10 @@ The methods on the response object (`res`) in the following table can send a res
|
||||
|
||||
<h2 id="app-route">app.route()</h2>
|
||||
|
||||
Chainable route handlers for a route path can be created using `app.route()`.
|
||||
Since the path is specified at a single location, it
|
||||
helps to create modular routes and reduce redundancy and typos. For more
|
||||
information on routes, see [Router() documentation](/4x/api.html#router).
|
||||
You can create chainable route handlers for a route path by using `app.route()`.
|
||||
Because the path is specified at a single location, creating modular routes is helpful, as is reducing redundancy and typos. For more information about routes, see: [Router() documentation](/4x/api.html#router).
|
||||
|
||||
Here is an example of chained route handlers defined using `app.route()`.
|
||||
Here is an example of chained route handlers that are defined by using `app.route()`.
|
||||
|
||||
~~~js
|
||||
app.route('/book')
|
||||
@@ -239,21 +237,17 @@ app.route('/book')
|
||||
|
||||
<h2 id="express-router">express.Router</h2>
|
||||
|
||||
The `express.Router` class can be used to create modular mountable
|
||||
route handlers. A `Router` instance is a complete middleware and
|
||||
routing system; for this reason it is often referred to as a "mini-app".
|
||||
The `express.Router` class can be used to create modular, mountable route handlers. A `Router` instance is a complete middleware and routing system; for this reason, it is often referred to as a "mini-app".
|
||||
|
||||
The following example creates a router as a module, loads a middleware in
|
||||
it, defines some routes, and mounts it on a path on the main app.
|
||||
The following example creates a router as a module, loads a middleware function in it, defines some routes, and mounts the router module on a path in the main app.
|
||||
|
||||
Create a router file named `birds.js` in the app directory,
|
||||
with the following content:
|
||||
Create a router file named `birds.js` in the app directory, with the following content:
|
||||
|
||||
~~~js
|
||||
var express = require('express');
|
||||
var router = express.Router();
|
||||
|
||||
// middleware specific to this router
|
||||
// middleware that is specific to this router
|
||||
router.use(function timeLog(req, res, next) {
|
||||
console.log('Time: ', Date.now());
|
||||
next();
|
||||
@@ -278,6 +272,5 @@ var birds = require('./birds');
|
||||
app.use('/birds', birds);
|
||||
~~~
|
||||
|
||||
The app will now be able to handle requests to `/birds` and
|
||||
`/birds/about`, along with calling the `timeLog`
|
||||
middleware specific to the route.
|
||||
The app will now be able to handle requests to `/birds` and `/birds/about`, as well as call the `timeLog` middleware function that is specific to the route.
|
||||
|
||||
|
||||
@@ -7,20 +7,20 @@ lang: en
|
||||
|
||||
# Using middleware
|
||||
|
||||
Express is a routing and middleware web framework with minimal functionality of its own: An Express application is essentially a series of middleware calls.
|
||||
Express is a routing and middleware web framework that has minimal functionality of its own: An Express application is essentially a series of middleware function calls.
|
||||
|
||||
_Middleware_ is a function with access to the [request object](/4x/api.html#req) (`req`), the [response object](/4x/api.html#res) (`res`), and the next middleware in the application's request-response cycle, commonly denoted by a variable named `next`.
|
||||
_Middleware_ functions are functions that have access to the [request object](/4x/api.html#req) (`req`), the [response object](/4x/api.html#res) (`res`), and the next middleware function in the application's request-response cycle. The next middleware function is commonly denoted by a variable named `next`.
|
||||
|
||||
Middleware can:
|
||||
Middleware functions can perform the following tasks:
|
||||
|
||||
- Execute any code.
|
||||
- Make changes to the request and the response objects.
|
||||
- End the request-response cycle.
|
||||
- Call the next middleware in the stack.
|
||||
* Execute any code.
|
||||
* Make changes to the request and the response objects.
|
||||
* End the request-response cycle.
|
||||
* Call the next middleware function in the stack.
|
||||
|
||||
If the current middleware does not end the request-response cycle, it must call `next()` to pass control to the next middleware, otherwise the request will be left hanging.
|
||||
If the current middleware function does not end the request-response cycle, it must call `next()` to pass control to the next middleware function. Otherwise, the request will be left hanging.
|
||||
|
||||
An Express application can use the following kinds of middleware:
|
||||
An Express application can use the following types of middleware:
|
||||
|
||||
- [Application-level middleware](#middleware.application)
|
||||
- [Router-level middleware](#middleware.router)
|
||||
@@ -29,39 +29,45 @@ An Express application can use the following kinds of middleware:
|
||||
- [Third-party middleware](#middleware.third-party)
|
||||
|
||||
You can load application-level and router-level middleware with an optional mount path.
|
||||
Also, you can load a series of middleware functions together, creating a sub-stack of the middleware system at a mount point.
|
||||
You can also load a series of middleware functions together, which creates a sub-stack of the middleware system at a mount point.
|
||||
|
||||
<h2 id='middleware.application'>Application-level middleware</h2>
|
||||
|
||||
Bind application-level middleware to an instance of the [app object](/4x/api.html#app) with `app.use()` and `app.METHOD()`,
|
||||
where `METHOD` is the HTTP method of the request that it handles, such as GET, PUT, POST, and so on, in lowercase.
|
||||
For example:
|
||||
Bind application-level middleware to an instance of the [app object](/4x/api.html#app) by using the `app.use()` and `app.METHOD()` functions, where `METHOD` is the HTTP method of the request that the middleware function handles (such as GET, PUT, or POST) in lowercase.
|
||||
|
||||
This example shows a middleware function with no mount path. The function is executed every time the app receives a request.
|
||||
|
||||
~~~js
|
||||
var app = express();
|
||||
|
||||
// a middleware with no mount path; gets executed for every request to the app
|
||||
app.use(function (req, res, next) {
|
||||
console.log('Time:', Date.now());
|
||||
next();
|
||||
});
|
||||
~~~
|
||||
|
||||
// a middleware mounted on /user/:id; will be executed for any type of HTTP request to /user/:id
|
||||
This example shows a middleware function mounted on the `/user/:id` path. The function is executed for any type of
|
||||
HTTP request on the `/user/:id` path.
|
||||
|
||||
~~~js
|
||||
app.use('/user/:id', function (req, res, next) {
|
||||
console.log('Request Type:', req.method);
|
||||
next();
|
||||
});
|
||||
~~~
|
||||
|
||||
// a route and its handler function (middleware system) which handles GET requests to /user/:id
|
||||
This example shows a route and its handler function (middleware system). The function handles GET requests to the `/user/:id` path.
|
||||
|
||||
~~~js
|
||||
app.get('/user/:id', function (req, res, next) {
|
||||
res.send('USER');
|
||||
});
|
||||
~~~
|
||||
|
||||
Here is an example of loading a series of middleware at a mount point with a mount path:
|
||||
Here is an example of loading a series of middleware functions at a mount point, with a mount path.
|
||||
It illustrates a middleware sub-stack that prints request info for any type of HTTP request to the `/user/:id` path.
|
||||
|
||||
~~~js
|
||||
// a middleware sub-stack which prints request info for any type of HTTP request to /user/:id
|
||||
app.use('/user/:id', function(req, res, next) {
|
||||
console.log('Request URL:', req.originalUrl);
|
||||
next();
|
||||
@@ -71,10 +77,11 @@ app.use('/user/:id', function(req, res, next) {
|
||||
});
|
||||
~~~
|
||||
|
||||
Route handlers enable you to define multiple routes for a path. The example below defines two routes for GET requests to `/user/:id`. The second router will not cause any problems, however it will never get called, because the first route ends the request-response cycle.
|
||||
Route handlers enable you to define multiple routes for a path. The example below defines two routes for GET requests to the `/user/:id` path. The second route will not cause any problems, but it will never get called because the first route ends the request-response cycle.
|
||||
|
||||
This example shows a middleware sub-stack that handles GET requests to the `/user/:id` path.
|
||||
|
||||
~~~js
|
||||
// a middleware sub-stack which handles GET requests to /user/:id
|
||||
app.get('/user/:id', function (req, res, next) {
|
||||
console.log('ID:', req.params.id);
|
||||
next();
|
||||
@@ -82,28 +89,29 @@ app.get('/user/:id', function (req, res, next) {
|
||||
res.send('User Info');
|
||||
});
|
||||
|
||||
// handler for /user/:id which prints the user id
|
||||
// handler for the /user/:id path, which prints the user ID
|
||||
app.get('/user/:id', function (req, res, next) {
|
||||
res.end(req.params.id);
|
||||
});
|
||||
~~~
|
||||
|
||||
To skip the rest of the middleware from a router middleware stack, call `next('route')` to pass control to the next route.
|
||||
**NOTE**: `next('route')` will work only in middleware loaded using `app.METHOD()` or `router.METHOD()`.
|
||||
To skip the rest of the middleware functions from a router middleware stack, call `next('route')` to pass control to the next route.
|
||||
**NOTE**: `next('route')` will work only in middleware functions that were loaded by using the `app.METHOD()` or `router.METHOD()` functions.
|
||||
|
||||
This example shows a middleware sub-stack that handles GET requests to the `/user/:id` path.
|
||||
|
||||
~~~js
|
||||
// a middleware sub-stack which handles GET requests to /user/:id
|
||||
app.get('/user/:id', function (req, res, next) {
|
||||
// if user id is 0, skip to the next route
|
||||
// if the user ID is 0, skip to the next route
|
||||
if (req.params.id == 0) next('route');
|
||||
// else pass the control to the next middleware in this stack
|
||||
// otherwise pass the control to the next middleware function in this stack
|
||||
else next(); //
|
||||
}, function (req, res, next) {
|
||||
// render a regular page
|
||||
res.render('regular');
|
||||
});
|
||||
|
||||
// handler for /user/:id which renders a special page
|
||||
// handler for the /user/:id path, which renders a special page
|
||||
app.get('/user/:id', function (req, res, next) {
|
||||
res.render('special');
|
||||
});
|
||||
@@ -111,27 +119,26 @@ app.get('/user/:id', function (req, res, next) {
|
||||
|
||||
<h2 id='middleware.router'>Router-level middleware</h2>
|
||||
|
||||
Router-level middleware works just like application-level middleware except it is bound to an instance of `express.Router()`.
|
||||
Router-level middleware works in the same way as application-level middleware, except it is bound to an instance of `express.Router()`.
|
||||
|
||||
~~~js
|
||||
var router = express.Router();
|
||||
~~~
|
||||
Load router-level middleware using `router.use()` and `router.METHOD()`.
|
||||
Load router-level middleware by using the `router.use()` and `router.METHOD()` functions.
|
||||
|
||||
The following example code replicates the middleware system shown above for application-level middleware
|
||||
using router-level middleware:
|
||||
The following example code replicates the middleware system that is shown above for application-level middleware, by using router-level middleware:
|
||||
|
||||
~~~js
|
||||
var app = express();
|
||||
var router = express.Router();
|
||||
|
||||
// a middleware with no mount path, gets executed for every request to the router
|
||||
// a middleware function with no mount path. This code is executed for every request to the router
|
||||
router.use(function (req, res, next) {
|
||||
console.log('Time:', Date.now());
|
||||
next();
|
||||
});
|
||||
|
||||
// a middleware sub-stack shows request info for any type of HTTP request to /user/:id
|
||||
// a middleware sub-stack shows request info for any type of HTTP request to the /user/:id path
|
||||
router.use('/user/:id', function(req, res, next) {
|
||||
console.log('Request URL:', req.originalUrl);
|
||||
next();
|
||||
@@ -140,18 +147,18 @@ router.use('/user/:id', function(req, res, next) {
|
||||
next();
|
||||
});
|
||||
|
||||
// a middleware sub-stack which handles GET requests to /user/:id
|
||||
// a middleware sub-stack that handles GET requests to the /user/:id path
|
||||
router.get('/user/:id', function (req, res, next) {
|
||||
// if user id is 0, skip to the next router
|
||||
// if the user ID is 0, skip to the next router
|
||||
if (req.params.id == 0) next('route');
|
||||
// else pass the control to the next middleware in this stack
|
||||
// otherwise pass control to the next middleware function in this stack
|
||||
else next(); //
|
||||
}, function (req, res, next) {
|
||||
// render a regular page
|
||||
res.render('regular');
|
||||
});
|
||||
|
||||
// handler for /user/:id which renders a special page
|
||||
// handler for the /user/:id path, which renders a special page
|
||||
router.get('/user/:id', function (req, res, next) {
|
||||
console.log(req.params.id);
|
||||
res.render('special');
|
||||
@@ -164,10 +171,10 @@ app.use('/', router);
|
||||
<h2 id='middleware.error-handling'>Error-handling middleware</h2>
|
||||
|
||||
<div class="doc-box doc-notice" markdown="1">
|
||||
Error-handling middleware always takes _four_ arguments. You must provide four arguments to identify it as an error-handling middleware. Even if you don't need to use the `next` object, you must specify it to maintain the signature, otherwise it will be interpreted as regular middleware and fail to handle errors.
|
||||
Error-handling middleware always takes _four_ arguments. You must provide four arguments to identify it as an error-handling middleware function. Even if you don't need to use the `next` object, you must specify it to maintain the signature. Otherwise, the `next` object will be interpreted as regular middleware and will fail to handle errors.
|
||||
</div>
|
||||
|
||||
Define error-handling middleware like other middleware, except with four arguments instead of three, specifically with the signature `(err, req, res, next)`):
|
||||
Define error-handling middleware functions in the same way as other middleware functions, except with four arguments instead of three, specifically with the signature `(err, req, res, next)`):
|
||||
|
||||
~~~js
|
||||
app.use(function(err, req, res, next) {
|
||||
@@ -176,20 +183,20 @@ app.use(function(err, req, res, next) {
|
||||
});
|
||||
~~~
|
||||
|
||||
For details about error-handling middleware, see [Error handling](/guide/error-handling.html).
|
||||
For details about error-handling middleware, see: [Error handling](/guide/error-handling.html).
|
||||
|
||||
<h2 id='middleware.built-in'>Built-in middleware</h2>
|
||||
|
||||
As of 4.x, Express no longer depends on [Connect](https://github.com/senchalabs/connect). Except for `express.static`, all of the middleware
|
||||
previously included with Express' are now in separate modules. Please view [the list of middleware](https://github.com/senchalabs/connect#middleware).
|
||||
Since version 4.x, Express no longer depends on [Connect](https://github.com/senchalabs/connect). With the exception of `express.static`, all of the middleware
|
||||
functions that were previously included with Express' are now in separate modules. Please view [the list of middleware functions](https://github.com/senchalabs/connect#middleware).
|
||||
|
||||
<h4 id='express.static'>express.static(root, [options])</h4>
|
||||
|
||||
Express' only built-in middleware is `express.static`. It is based on [serve-static](https://github.com/expressjs/serve-static), and is responsible for serving the static assets of an Express application.
|
||||
The only built-in middleware function in Express is `express.static`. This function is based on [serve-static](https://github.com/expressjs/serve-static), and is responsible for serving the static assets of an Express application.
|
||||
|
||||
The `root` argument specifies the root directory from which to serve static assets.
|
||||
|
||||
The optional `options` object can have the following properties.
|
||||
The optional `options` object can have the following properties:
|
||||
|
||||
| Property | Description | Type | Default |
|
||||
|---------------|-----------------------------------------------------------------------|-------------|-----------------|
|
||||
@@ -198,11 +205,11 @@ The optional `options` object can have the following properties.
|
||||
| `extensions` | Sets file extension fallbacks. | Array | `[]` |
|
||||
| `index` | Sends directory index file. Set `false` to disable directory indexing. | Mixed | "index.html" |
|
||||
`lastModified` | Set the `Last-Modified` header to the last modified date of the file on the OS. Possible values are `true` or `false`. | Boolean | `true` |
|
||||
| `maxAge` | Set the max-age property of the Cache-Control header in milliseconds or a string in [ms format](https://www.npmjs.org/package/ms) | Number | 0 |
|
||||
| `maxAge` | Set the max-age property of the Cache-Control header, in milliseconds or a string in [ms format](https://www.npmjs.org/package/ms) | Number | 0 |
|
||||
| `redirect` | Redirect to trailing "/" when the pathname is a directory. | Boolean | `true` |
|
||||
| `setHeaders` | Function for setting HTTP headers to serve with the file. | Function | |
|
||||
|
||||
Here is an example of using the `express.static` middleware with an elaborate options object.
|
||||
Here is an example of using the `express.static` middleware function with an elaborate options object:
|
||||
|
||||
~~~js
|
||||
var options = {
|
||||
@@ -220,7 +227,7 @@ var options = {
|
||||
app.use(express.static('public', options));
|
||||
~~~
|
||||
|
||||
You can have more than one static directory per app.
|
||||
You can have more than one static directory per app:
|
||||
|
||||
~~~js
|
||||
app.use(express.static('public'));
|
||||
@@ -228,15 +235,15 @@ app.use(express.static('uploads'));
|
||||
app.use(express.static('files'));
|
||||
~~~
|
||||
|
||||
For more details about `serve-static` and its options, see the [serve-static](https://github.com/expressjs/serve-static) documentation.
|
||||
For more details about the `serve-static` function and its options, see: [serve-static](https://github.com/expressjs/serve-static) documentation.
|
||||
|
||||
<h2 id='middleware.third-party'>Third-party middleware</h2>
|
||||
|
||||
Use third-party middleware to add functionality to Express apps.
|
||||
|
||||
Install the Node module for the required functionality and load it in your app at the application level or at the router level.
|
||||
Install the Node.js module for the required functionality, then load it in your app at the application level or at the router level.
|
||||
|
||||
The following example illustrates installing and loading cookie-parsing middleware `cookie-parser`.
|
||||
The following example illustrates installing and loading the cookie-parsing middleware function `cookie-parser`.
|
||||
|
||||
~~~sh
|
||||
$ npm install cookie-parser
|
||||
@@ -247,8 +254,8 @@ var express = require('express');
|
||||
var app = express();
|
||||
var cookieParser = require('cookie-parser');
|
||||
|
||||
// load the cookie parsing middleware
|
||||
// load the cookie-parsing middleware
|
||||
app.use(cookieParser());
|
||||
~~~
|
||||
|
||||
See [Third-party middleware](../resources/middleware.html) for a partial list of third-party middleware commonly used with Express.
|
||||
For a partial list of third-party middleware functions that are commonly used with Express, see: [Third-party middleware](../resources/middleware.html).
|
||||
|
||||
18
guide/using-template-engines.md
Normal file → Executable file
18
guide/using-template-engines.md
Normal file → Executable file
@@ -7,30 +7,30 @@ lang: en
|
||||
|
||||
# Using template engines with Express
|
||||
|
||||
Before Express can render template files, the following application settings have to be set.
|
||||
Before Express can render template files, the following application settings must be set:
|
||||
|
||||
* `views`, the directory where the template files are located. Eg: `app.set('views', './views')`
|
||||
* `view engine`, the template engine to use. Eg: `app.set('view engine', 'jade')`
|
||||
|
||||
Then install the corresponding template engine npm package.
|
||||
Then install the corresponding template engine npm package:
|
||||
|
||||
~~~sh
|
||||
$ npm install jade --save
|
||||
~~~
|
||||
|
||||
<div class="doc-box doc-notice" markdown="1">
|
||||
Express-compliant template engines such as Jade, export a function named `__express(filePath, options, callback)`, which is called by `res.render()` to render the template code.
|
||||
Express-compliant template engines such as Jade export a function named `__express(filePath, options, callback)`, which is called by the `res.render()` function to render the template code.
|
||||
|
||||
Some template engines do not follow this convention, the [Consolidate.js](https://www.npmjs.org/package/consolidate) library was created to map all of node's popular template engines to follow this convention, thus allowing them to work seamlessly within Express.
|
||||
Some template engines do not follow this convention. The [Consolidate.js](https://www.npmjs.org/package/consolidate) library follows this convention by mapping all of the popular Node.js template engines, and therefore works seamlessly within Express.
|
||||
</div>
|
||||
|
||||
Once the view engine is set, you don't have to explicitly specify the engine or load the template engine module in your app, Express loads it internally as shown below, for the example above.
|
||||
After the view engine is set, you don't have to specify the engine or load the template engine module in your app; Express loads the module internally, as shown below (for the above example).
|
||||
|
||||
~~~js
|
||||
app.set('view engine', 'jade');
|
||||
~~~
|
||||
|
||||
Create a Jade template file named "index.jade" in the views directory, with the following content.
|
||||
Create a Jade template file named `index.jade` in the `views` directory, with the following content:
|
||||
|
||||
~~~js
|
||||
html
|
||||
@@ -40,7 +40,7 @@ html
|
||||
h1!= message
|
||||
~~~
|
||||
|
||||
Then create a route to render the "index.jade" file. If the `view engine` property is not set, you will have to specify the extension of the view file, else you can omit it.
|
||||
Then create a route to render the `index.jade` file. If the `view engine` property is not set, you must specify the extension of the `view` file. Otherwise, you can omit it.
|
||||
|
||||
~~~js
|
||||
app.get('/', function (req, res) {
|
||||
@@ -48,6 +48,6 @@ app.get('/', function (req, res) {
|
||||
});
|
||||
~~~
|
||||
|
||||
On making a request to the home page, "index.jade" will be rendered as HTML.
|
||||
When you make a request to the home page, the `index.jade` file will be rendered as HTML.
|
||||
|
||||
To better understand how template engines work in Express, read ["Developing template engines for Express"](/advanced/developing-template-engines.html).
|
||||
To learn more about how template engines work in Express, see: ["Developing template engines for Express"](/advanced/developing-template-engines.html).
|
||||
|
||||
40
guide/writing-middleware.md
Normal file → Executable file
40
guide/writing-middleware.md
Normal file → Executable file
@@ -9,22 +9,22 @@ lang: en
|
||||
|
||||
<h2>Overview</h2>
|
||||
|
||||
Middleware is a function with access to the request object (`req`), the response object (`res`), and the next middleware in the application's request-response cycle, commonly denoted by a variable named `next`.
|
||||
_Middleware_ functions are functions that have access to the [request object](/4x/api.html#req) (`req`), the [response object](/4x/api.html#res) (`res`), and the next middleware function in the application's request-response cycle. The next middleware function is commonly denoted by a variable named `next`.
|
||||
|
||||
Middleware can:
|
||||
Middleware functions can perform the following tasks:
|
||||
|
||||
* Execute any code.
|
||||
* Make changes to the request and the response objects.
|
||||
* End the request-response cycle.
|
||||
* Call the next middleware in the stack.
|
||||
|
||||
If the current middleware does not end the request-response cycle, it must call `next()` to pass control to the next middleware, otherwise the request will be left hanging.
|
||||
If the current middleware function does not end the request-response cycle, it must call `next()` to pass control to the next middleware function. Otherwise, the request will be left hanging.
|
||||
|
||||
The following figure illustrates the elements of a middleware function call:
|
||||
The following figure shows the elements of a middleware function call:
|
||||
|
||||
<img class="outlined-img" src="/images/express-mw.png" />
|
||||
|
||||
To learn how to write and use Express middleware, we will write two middleware for the following simple "Hello world" app:
|
||||
To learn how to write and use Express middleware functions, we will write two middleware functions for the following, simple "Hello world" app:
|
||||
|
||||
~~~js
|
||||
var express = require('express');
|
||||
@@ -39,7 +39,7 @@ app.listen(3000);
|
||||
|
||||
<h2>Development</h2>
|
||||
|
||||
Here is a simple example of middleware called "myLogger". All it does is print "LOGGED", when a request to the app passes through it. The middleware is assigned to a variable named `myLogger`.
|
||||
Here is a simple example of a middleware function called "myLogger". This function just prints "LOGGED" when a request to the app passes through it. The middleware function is assigned to a variable named `myLogger`.
|
||||
|
||||
~~~js
|
||||
var myLogger = function (req, res, next) {
|
||||
@@ -49,14 +49,12 @@ var myLogger = function (req, res, next) {
|
||||
~~~
|
||||
|
||||
<div class="doc-box doc-notice" markdown="1">
|
||||
Notice the call above to `next()`. Calling this function invokes the next middleware in the app.
|
||||
The `next()` function is not a part of the Node or Express API, but rather is the third argument
|
||||
passed to the middleware function. It could be called anything, but by convention it is always called "next".
|
||||
To avoid confusion, always follow this convention.
|
||||
Notice the call above to `next()`. Calling this function invokes the next middleware function in the app.
|
||||
The `next()` function is not a part of the Node.js or Express API, but is the third argument that is passed to the middleware function. The `next()` function could be named anything, but by convention it is always named "next". To avoid confusion, always use this convention.
|
||||
</div>
|
||||
|
||||
To load the middleware, call `app.use()` with the middleware function.
|
||||
For example, the following code loads this middleware before the route to the root path (/).
|
||||
To load the middleware function, call `app.use()`, specifying the middleware function.
|
||||
For example, the following code loads the `myLogger` middleware function before the route to the root path (/).
|
||||
|
||||
~~~js
|
||||
var express = require('express');
|
||||
@@ -76,15 +74,15 @@ app.get('/', function (req, res) {
|
||||
app.listen(3000);
|
||||
~~~
|
||||
|
||||
Now every time the app receives a request, it will print "LOGGED" to the terminal.
|
||||
Every time the app receives a request, it prints the message "LOGGED" to the terminal.
|
||||
|
||||
The order of middleware loading is important: middleware loaded first is executed first.
|
||||
The order of middleware loading is important: middleware functions that are loaded first are also executed first.
|
||||
|
||||
If myLogger was loaded after the route to the root path, the request would have never reached it, and the app wouldn't print "LOGGED", because the route handler of the root path would have terminated the request-response cycle.
|
||||
If `myLogger` is loaded after the route to the root path, the request never reaches it and the app doesn't print "LOGGED", because the route handler of the root path terminates the request-response cycle.
|
||||
|
||||
The middleware myLogger simply printed a message and passed on the request to the next middleware in the stack by calling `next()`.
|
||||
The middleware function `myLogger` simply prints a message, then passes on the request to the next middleware function in the stack by calling the `next()` function.
|
||||
|
||||
The next example adds a property called `requestTime` to the request object. So, we'll call this middleware "requestTime".
|
||||
The next example adds a property called `requestTime` to the request object. We'll name this middleware function "requestTime".
|
||||
|
||||
~~~js
|
||||
var requestTime = function (req, res, next) {
|
||||
@@ -93,7 +91,7 @@ var requestTime = function (req, res, next) {
|
||||
};
|
||||
~~~
|
||||
|
||||
The app now uses the requestTime middleware, and the callback function of the root path route uses the property that the middleware adds to `req` (the request object).
|
||||
The app now uses the `requestTime` middleware function. Also, the callback function of the root path route uses the property that the middleware function adds to `req` (the request object).
|
||||
|
||||
~~~js
|
||||
var express = require('express');
|
||||
@@ -115,8 +113,8 @@ app.get('/', function (req, res) {
|
||||
app.listen(3000);
|
||||
~~~
|
||||
|
||||
On making a request to the root of the app now, the app displays the timestamp of request in the browser.
|
||||
When you make a request to the root of the app, the app now displays the timestamp of your request in the browser.
|
||||
|
||||
With access to the request object, the response object, the next middleware in stack, and the whole Node.js API, the possibilities with middleware are endless.
|
||||
Because you have access to the request object, the response object, the next middleware function in the stack, and the whole Node.js API, the possibilities with middleware functions are endless.
|
||||
|
||||
For more information about Express middleware, refer to the article "[Using Express middleware](/guide/using-middleware.html)".
|
||||
For more information about Express middleware, see: "[Using Express middleware](/guide/using-middleware.html)".
|
||||
2
index.md
Normal file → Executable file
2
index.md
Normal file → Executable file
@@ -40,7 +40,7 @@ lang: en
|
||||
</div>
|
||||
|
||||
<div id="performance">
|
||||
<h3>Performance</h3> Express provides a thin layer of fundamental web application features, without obscuring Node features that you know and love.
|
||||
<h3>Performance</h3> Express provides a thin layer of fundamental web application features, without obscuring Node.js features that you know and love.
|
||||
</div>
|
||||
|
||||
<div id="sponsorship">
|
||||
|
||||
5
resources/community.md
Normal file → Executable file
5
resources/community.md
Normal file → Executable file
@@ -26,7 +26,7 @@ feedback.
|
||||
##Examples
|
||||
|
||||
View dozens of Express application [examples](https://github.com/strongloop/express/tree/master/examples)
|
||||
in the repo covering everything from API design and auth
|
||||
in the repository covering everything from API design and authentication
|
||||
to template engine integration.
|
||||
|
||||
##Issues
|
||||
@@ -37,5 +37,6 @@ a feature request open a ticket in the [issue queue](https://github.com/stronglo
|
||||
##Third Party
|
||||
|
||||
Our vibrant community has created a large variety of extensions,
|
||||
[middleware](/resources/middleware.html) and higher level frameworks. Check them out in the
|
||||
[middleware modules](/resources/middleware.html) and higher level frameworks. Check them out in the
|
||||
[wiki](https://github.com/strongloop/express/wiki).
|
||||
|
||||
|
||||
18
resources/glossary.md
Normal file → Executable file
18
resources/glossary.md
Normal file → Executable file
@@ -11,23 +11,23 @@ lang: en
|
||||
|
||||
### application
|
||||
|
||||
In general, one or more programs designed to carry out operations for a specific purpose. In the context of Express, a program that uses the Express API running on the Node.js platform. May also refer to an [app object](/api.html#express).
|
||||
In general, one or more programs that are designed to carry out operations for a specific purpose. In the context of Express, a program that uses the Express API running on the Node.js platform. Might also refer to an [app object](/api.html#express).
|
||||
|
||||
### API
|
||||
|
||||
Application programming interface. Spell out on first use.
|
||||
Application programming interface. Spell out the abbreviation when it is first used.
|
||||
|
||||
### Express
|
||||
|
||||
A fast, un-opinionated, minimalist web framework for Node.js applications. In general, prefer simply "Express" to "Express.js," though the latter is acceptable.
|
||||
A fast, un-opinionated, minimalist web framework for Node.js applications. In general, "Express" is preferred to "Express.js," though the latter is acceptable.
|
||||
|
||||
### libuv
|
||||
|
||||
Multi-platform support library with focus on asynchronous I/O, primarily developed for use by Node.js.
|
||||
A multi-platform support library which focuses on asynchronous I/O, primarily developed for use by Node.js.
|
||||
|
||||
### middleware
|
||||
|
||||
A function invoked by the Express routing layer before the final request handler, and thus sits in the middle between a raw request and the final intended route. A few fine points of terminology around middleware:
|
||||
A function that is invoked by the Express routing layer before the final request handler, and thus sits in the middle between a raw request and the final intended route. A few fine points of terminology around middleware:
|
||||
|
||||
* `var foo = require('middleware')` is called _requiring_ or _using_ a Node.js module. Then the statement `var mw = foo()` typically returns the middleware.
|
||||
* `app.use(mw)` is called _adding the middleware to the global processing stack_.
|
||||
@@ -35,19 +35,19 @@ A function invoked by the Express routing layer before the final request handler
|
||||
|
||||
### Node.js
|
||||
|
||||
Software platform used to build scalable network applications. Node.js uses JavaScript as its scripting language, and achieves high throughput via non-blocking I/O and a single-threaded event loop. See [nodejs.org](http://nodejs.org/). **Usage note**: Initially, "Node.js," thereafter "Node".
|
||||
A software platform that is used to build scalable network applications. Node.js uses JavaScript as its scripting language, and achieves high throughput via non-blocking I/O and a single-threaded event loop. See [nodejs.org](http://nodejs.org/). **Usage note**: Initially, "Node.js," thereafter "Node".
|
||||
|
||||
### open-source, open source
|
||||
|
||||
When used as an adjective, hyphenate; for example: "This is open-source software." See [Open-source software on Wikipedia](http://en.wikipedia.org/wiki/Open-source_software). Note: Although it is common not to hyphenate this term, we are using the standard English rules for hyphenating a compound adjective
|
||||
When used as an adjective, hyphenate; for example: "This is open-source software." See [Open-source software on Wikipedia](http://en.wikipedia.org/wiki/Open-source_software). Note: Although it is common not to hyphenate this term, we are using the standard English rules for hyphenating a compound adjective.
|
||||
|
||||
### request
|
||||
|
||||
An HTTP request. A client submits an HTTP request message to a server, which returns an response. Must use one of several [request methods](https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol#Request_methods) such as GET, POST, and so on.
|
||||
An HTTP request. A client submits an HTTP request message to a server, which returns a response. The request must use one of several [request methods](https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol#Request_methods) such as GET, POST, and so on.
|
||||
|
||||
### response
|
||||
|
||||
An HTTP response. A server returns an HTTP response message to the client. The response contains completion status information about the request and may also contain requested content in its message body.
|
||||
An HTTP response. A server returns an HTTP response message to the client. The response contains completion status information about the request and might also contain requested content in its message body.
|
||||
|
||||
### route
|
||||
|
||||
|
||||
35
resources/middleware.md
Normal file → Executable file
35
resources/middleware.md
Normal file → Executable file
@@ -14,36 +14,35 @@ Here are some Express middleware modules:
|
||||
- [body](https://github.com/raynos/body)
|
||||
- [co-body](https://github.com/visionmedia/co-body)
|
||||
- [raw-body](https://github.com/stream-utils/raw-body)
|
||||
- [compression](https://github.com/expressjs/compression) - previously `express.compress`
|
||||
- [connect-image-optimus](https://github.com/msemenistyi/connect-image-optimus): Connect/Express middleware for optimal image serving. Switches to webp/jpegxr if possible.
|
||||
- [compression](https://github.com/expressjs/compression): previously `express.compress`
|
||||
- [connect-image-optimus](https://github.com/msemenistyi/connect-image-optimus): Connect/Express middleware modules for optimal image serving. Switches images to `.webp` or `.jxr`, if possible.
|
||||
- [connect-timeout](https://github.com/expressjs/timeout): previously `express.timeout`
|
||||
- [cookie-parser](https://github.com/expressjs/cookie-parser): previously `express.cookieParser`
|
||||
- [cookie-session](https://github.com/expressjs/cookie-session): previously `express.cookieSession`
|
||||
- [csurf](https://github.com/expressjs/csurf): previously `express.csrf`
|
||||
- [errorhandler](https://github.com/expressjs/errorhandler): previously `express.errorHandler`
|
||||
- [express-debug](https://github.com/devoidfury/express-debug): unobtrusive development tool that adds a tab with information about req, session, locals, and more to your application.
|
||||
- [express-partial-response](https://github.com/nemtsov/express-partial-response): Express middleware for filtering-out parts of JSON responses based on the `fields` query-string; using Google API's Partial Response.
|
||||
- [express-debug](https://github.com/devoidfury/express-debug): unobtrusive development tool that adds a tab with information about template variables (locals), current session, useful request data, and more to your application.
|
||||
- [express-partial-response](https://github.com/nemtsov/express-partial-response): Express middleware module for filtering-out parts of JSON responses based on the `fields` query-string; by using Google API's Partial Response.
|
||||
- [express-session](https://github.com/expressjs/session): previously `express.session`
|
||||
- [express-simple-cdn](https://github.com/jamiesteven/express-simple-cdn): easily use a CDN for your static assets, with multiple host support (ex. cdn1.host.com, cdn2.host.com).
|
||||
- [express-slash](https://github.com/ericf/express-slash): Express middleware for people who are strict about trailing slashes.
|
||||
- [express-stormpath](https://github.com/stormpath/stormpath-express): Express middleware for user storage, authentication, authorization, SSO, and data security.
|
||||
- [express-uncapitalize](https://github.com/jamiesteven/express-uncapitalize): redirect HTTP requests containing uppercase to a canonical lowercase form.
|
||||
- [helmet](https://github.com/helmetjs/helmet): help secure your apps by setting various HTTP headers
|
||||
- [join-io](https://github.com/coderaiser/join-io "join-io"): join files on a fly to reduce requests count
|
||||
- [express-simple-cdn](https://github.com/jamiesteven/express-simple-cdn): Express middleware module for using a CDN for static assets, with multiple host support (For example: cdn1.host.com, cdn2.host.com).
|
||||
- [express-slash](https://github.com/ericf/express-slash): Express middleware module for people who are strict about trailing slashes.
|
||||
- [express-stormpath](https://github.com/stormpath/stormpath-express): Express middleware module for user storage, authentication, authorization, SSO, and data security.
|
||||
- [express-uncapitalize](https://github.com/jamiesteven/express-uncapitalize): middleware module for redirecting HTTP requests containing uppercase to a canonical lowercase form.
|
||||
- [helmet](https://github.com/helmetjs/helmet): module to help secure your apps by setting various HTTP headers.
|
||||
- [join-io](https://github.com/coderaiser/join-io "join-io"): module for joining files on the fly to reduce the requests count.
|
||||
- [method-override](https://github.com/expressjs/method-override): previously `express.methodOverride`
|
||||
- [morgan](https://github.com/expressjs/morgan): previously `logger`
|
||||
- [passport](https://github.com/jaredhanson/passport): Express middleware for authentication.
|
||||
- [passport](https://github.com/jaredhanson/passport): Express middleware module for authentication.
|
||||
- [response-time](https://github.com/expressjs/response-time): previously `express.responseTime`
|
||||
- [serve-favicon](https://github.com/expressjs/serve-favicon): previously `express.favicon`
|
||||
- [serve-index](https://github.com/expressjs/serve-index): previously `express.directory`
|
||||
- [serve-static](https://github.com/expressjs/serve-static): for serving static content
|
||||
- [static-expiry](https://github.com/paulwalker/connect-static-expiry): fingerprinted URLs/Caching Headers for static assets including external domain(s) support.
|
||||
- [serve-static](https://github.com/expressjs/serve-static): module for serving static content.
|
||||
- [static-expiry](https://github.com/paulwalker/connect-static-expiry): fingerprinted URLs or Caching Headers for static assets including support for one or more external domains.
|
||||
- [vhost](https://github.com/expressjs/vhost): previously `express.vhost`
|
||||
- [view-helpers](https://github.com/madhums/node-view-helpers): An express middleware that provides common helper methods to the views.
|
||||
- [sriracha-admin](https://github.com/hdngr/siracha): An express middleware that dynamically generates an admin site for Mongoose.
|
||||
- [view-helpers](https://github.com/madhums/node-view-helpers): Express middleware module that provides common helper methods to the views.
|
||||
- [sriracha-admin](https://github.com/hdngr/siracha): Express middleware module that dynamically generates an admin site for Mongoose.
|
||||
|
||||
Some middleware previously included with Connect are no longer supported by the Connect/Express team,
|
||||
and are replaced by an alternative module, or should be superseded by a better module. Use one of these alternatives instead:
|
||||
Some middleware modules previously included with Connect are no longer supported by the Connect/Express team. These modules are replaced by an alternative module, or should be superseded by a better module. Use one of the following alternatives:
|
||||
|
||||
- express.cookieParser
|
||||
- [cookies](https://github.com/jed/cookies) and [keygrip](https://github.com/jed/keygrip)
|
||||
@@ -59,6 +58,6 @@ and are replaced by an alternative module, or should be superseded by a better m
|
||||
- [st](https://github.com/isaacs/st)
|
||||
- [connect-static](https://github.com/andrewrk/connect-static)
|
||||
|
||||
For more middleware, see also:
|
||||
For more middleware modules, see:
|
||||
- [http-framework](https://github.com/Raynos/http-framework/wiki/Modules)
|
||||
- [expressjs](https://github.com/expressjs)
|
||||
|
||||
8
starter/basic-routing.md
Normal file → Executable file
8
starter/basic-routing.md
Normal file → Executable file
@@ -9,15 +9,15 @@ lang: en
|
||||
|
||||
This tutorial is a basic introduction to routing with Express. Routing refers to determining how an application responds to a client request to a particular endpoint, which is a URI (or path) and a specific HTTP request method (GET, POST, and so on).
|
||||
|
||||
Each route can have one or more handler functions, which is / are executed when the route is matched.
|
||||
Each route can have one or more handler functions, which are executed when the route is matched.
|
||||
|
||||
Route definition takes the following structure `app.METHOD(PATH, HANDLER)`, where `app` is an instance of `express`, `METHOD` is an [HTTP request method](http://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol), `PATH` is a path on the server, and `HANDLER` is the function executed when the route is matched.
|
||||
|
||||
<div class="doc-box doc-notice" markdown="1">
|
||||
This tutorial assumes that an instance of `express` named `app` is created and the server is running. If you are not familiar with creating an app and starting it, refer to the [Hello world example](/starter/hello-world.html).
|
||||
This tutorial assumes that an instance of `express` named `app` is created and the server is running. If you are not familiar with creating an app and starting it, see the [Hello world example](/starter/hello-world.html).
|
||||
</div>
|
||||
|
||||
The following code illustrates some example routes in an app.
|
||||
The following code illustrates some example routes in an app:
|
||||
|
||||
~~~js
|
||||
// respond with "Hello World!" on the homepage
|
||||
@@ -41,4 +41,4 @@ app.delete('/user', function (req, res) {
|
||||
});
|
||||
~~~
|
||||
|
||||
For more details about routing, refer to the [routing guide](/guide/routing.html).
|
||||
For more details about routing, see the [routing guide](/guide/routing.html).
|
||||
|
||||
38
starter/faq.md
Normal file → Executable file
38
starter/faq.md
Normal file → Executable file
@@ -9,11 +9,11 @@ lang: en
|
||||
|
||||
## How should I structure my application?
|
||||
|
||||
There is no definitive answer to this question. It depends
|
||||
on the scale of your application and the team involved. To be as
|
||||
There is no definitive answer to this question. The answer depends
|
||||
on the scale of your application and the team that is involved. To be as
|
||||
flexible as possible, Express makes no assumptions in terms of structure.
|
||||
|
||||
Routes and other application-specific logic may live in as many files
|
||||
Routes and other application-specific logic can live in as many files
|
||||
as you wish, in any directory structure you prefer. View the following
|
||||
examples for inspiration:
|
||||
|
||||
@@ -27,15 +27,15 @@ Also, there are third-party extensions for Express, which simplify some of these
|
||||
|
||||
## How do I define models?
|
||||
|
||||
Express has no notion of a database at all. This is
|
||||
Express has no notion of a database. This concept is
|
||||
left up to third-party Node modules, allowing you to
|
||||
interface with nearly any database.
|
||||
|
||||
See [LoopBack](http://loopback.io) for an Express-based framework centered around models.
|
||||
See [LoopBack](http://loopback.io) for an Express-based framework that is centered around models.
|
||||
|
||||
## How can I authenticate users?
|
||||
|
||||
This is another opinionated area that Express does not
|
||||
Authentication is another opinionated area that Express does not
|
||||
venture into. You may use any authentication scheme you wish.
|
||||
For a simple username / password scheme, see [this example](https://github.com/strongloop/express/tree/master/examples/auth).
|
||||
|
||||
@@ -45,17 +45,17 @@ For a simple username / password scheme, see [this example](https://github.com/s
|
||||
Express supports any template engine that conforms with the `(path, locals, callback)` signature.
|
||||
To normalize template engine interfaces and caching, see the
|
||||
[consolidate.js](https://github.com/visionmedia/consolidate.js)
|
||||
project for support. Unlisted template engines may still support the Express signature.
|
||||
project for support. Unlisted template engines might still support the Express signature.
|
||||
|
||||
## How do you handle 404s?
|
||||
## How do you handle 404 responses?
|
||||
|
||||
In Express, 404s are not the result of an error. Therefore,
|
||||
the error-handler middleware will not capture 404s. This is
|
||||
because a 404 is simply the absence of additional work to do;
|
||||
in other words, Express has executed all middleware / routes,
|
||||
In Express, 404 responses are not the result of an error, so
|
||||
the error-handler middleware will not capture them. This behavior is
|
||||
because a 404 response simply indicates the absence of additional work to do;
|
||||
in other words, Express has executed all middleware functions and routes,
|
||||
and found that none of them responded. All you need to
|
||||
do is add a middleware at the very bottom (below all others)
|
||||
to handle a 404:
|
||||
do is add a middleware function at the very bottom of the stack (below all other functions)
|
||||
to handle a 404 response:
|
||||
|
||||
~~~js
|
||||
app.use(function(req, res, next) {
|
||||
@@ -65,7 +65,7 @@ app.use(function(req, res, next) {
|
||||
|
||||
## How do you setup an error handler?
|
||||
|
||||
You define error-handling middleware the same way as other middleware,
|
||||
You define error-handling middleware in the same way as other middleware,
|
||||
except with four arguments instead of three; specifically with the signature `(err, req, res, next)`:
|
||||
|
||||
~~~js
|
||||
@@ -79,7 +79,7 @@ For more information, see [Error handling](/guide/error-handling.html).
|
||||
|
||||
## How do I render plain HTML?
|
||||
|
||||
You don't! There's no need to "render" HTML with `res.render()`.
|
||||
If you have a specific file, use `res.sendFile()`.
|
||||
If you are serving many assets from a directory use the `express.static()`
|
||||
middleware.
|
||||
You don't! There's no need to "render" HTML with the `res.render()` function.
|
||||
If you have a specific file, use the `res.sendFile()` function.
|
||||
If you are serving many assets from a directory, use the `express.static()`
|
||||
middleware function.
|
||||
|
||||
24
starter/generator.md
Normal file → Executable file
24
starter/generator.md
Normal file → Executable file
@@ -9,7 +9,7 @@ lang: en
|
||||
|
||||
Use the application generator tool, `express`, to quickly create an application skeleton.
|
||||
|
||||
Install it with the following command.
|
||||
Install `express` with the following command:
|
||||
|
||||
~~~sh
|
||||
$ npm install express-generator -g
|
||||
@@ -34,7 +34,7 @@ $ express -h
|
||||
-f, --force force on non-empty directory
|
||||
~~~
|
||||
|
||||
For example, the following creates an Express app named _myapp_ in the current working directory.
|
||||
For example, the following creates an Express app named _myapp_ in the current working directory:
|
||||
|
||||
~~~sh
|
||||
$ express myapp
|
||||
@@ -65,7 +65,7 @@ $ cd myapp
|
||||
$ npm install
|
||||
~~~
|
||||
|
||||
Run the app (on MacOS or Linux):
|
||||
On MacOS or Linux, run the app with this command:
|
||||
|
||||
~~~sh
|
||||
$ DEBUG=myapp:* npm start
|
||||
@@ -79,22 +79,22 @@ On Windows, use this command:
|
||||
|
||||
Then load `http://localhost:3000/` in your browser to access the app.
|
||||
|
||||
The generated app directory structure looks like the following.
|
||||
The generated app has the following directory structure:
|
||||
|
||||
~~~sh
|
||||
.
|
||||
├── app.js
|
||||
├── bin
|
||||
│ └── www
|
||||
│ └── www
|
||||
├── package.json
|
||||
├── public
|
||||
│ ├── images
|
||||
│ ├── javascripts
|
||||
│ └── stylesheets
|
||||
│ └── style.css
|
||||
│ ├── images
|
||||
│ ├── javascripts
|
||||
│ └── stylesheets
|
||||
│ └── style.css
|
||||
├── routes
|
||||
│ ├── index.js
|
||||
│ └── users.js
|
||||
│ ├── index.js
|
||||
│ └── users.js
|
||||
└── views
|
||||
├── error.jade
|
||||
├── index.jade
|
||||
@@ -104,5 +104,5 @@ The generated app directory structure looks like the following.
|
||||
~~~
|
||||
|
||||
<div class="doc-box doc-info" markdown="1">
|
||||
The app structure generated by the generator is just one of the multiple ways of structuring Express apps. Feel free to use it or to modify it to best suit your needs.
|
||||
The app structure created by the generator is just one of many ways to structure Express apps. Feel free to use this structure or modify it to best suit your needs.
|
||||
</div>
|
||||
|
||||
9
starter/hello-world.md
Normal file → Executable file
9
starter/hello-world.md
Normal file → Executable file
@@ -11,9 +11,9 @@ lang: en
|
||||
This is essentially going to be the simplest Express app you can create. It is a single file app — _not_ what you'd get if you use the [Express generator](/starter/generator.html), which creates the scaffolding for a full app with numerous JavaScript files, Jade templates, and sub-directories for various purposes.
|
||||
</div>
|
||||
|
||||
First create a directory named `myapp`, and run `npm init` in it. Then install `express` as a dependency, as per the [installation guide](/starter/installing.html).
|
||||
First create a directory named `myapp`, change to it and run `npm init`. Then install `express` as a dependency, as per the [installation guide](/starter/installing.html).
|
||||
|
||||
In the `myapp` directory, create a file named `app.js` and add the following code to it:
|
||||
In the `myapp` directory, create a file named `app.js` and add the following code:
|
||||
|
||||
~~~js
|
||||
var express = require('express');
|
||||
@@ -31,7 +31,7 @@ var server = app.listen(3000, function () {
|
||||
});
|
||||
~~~
|
||||
|
||||
The app starts a server and listens on port 3000 for connection. It will respond with "Hello World!" for requests
|
||||
The app starts a server and listens on port 3000 for connections. The app responds with "Hello World!" for requests
|
||||
to the root URL (`/`) or _route_. For every other path, it will respond with a **404 Not Found**.
|
||||
|
||||
<div class="doc-box doc-notice" markdown="1">
|
||||
@@ -39,10 +39,11 @@ The `req` (request) and `res` (response) are the exact same objects that Node pr
|
||||
`req.pipe()`, `req.on('data', callback)`, and anything else you would do without Express involved.
|
||||
</div>
|
||||
|
||||
Run the app with the following command.
|
||||
Run the app with the following command:
|
||||
|
||||
~~~ sh
|
||||
$ node app.js
|
||||
~~~
|
||||
|
||||
Then, load [http://localhost:3000/](http://localhost:3000/) in a browser to see the output.
|
||||
|
||||
|
||||
15
starter/installing.md
Normal file → Executable file
15
starter/installing.md
Normal file → Executable file
@@ -7,8 +7,7 @@ lang: en
|
||||
|
||||
# Installing
|
||||
|
||||
Assuming you've already installed [Node.js](https://nodejs.org/), create a directory to hold your application,
|
||||
and make that your working directory.
|
||||
Assuming you've already installed [Node.js](https://nodejs.org/), create a directory to hold your application, and make that your working directory.
|
||||
|
||||
~~~sh
|
||||
$ mkdir myapp
|
||||
@@ -22,22 +21,22 @@ For more information on how `package.json` works, see [Specifics of npm's packag
|
||||
$ npm init
|
||||
~~~
|
||||
|
||||
This command will prompt your for a number of things such as the name and version of your application.
|
||||
For now, you can simply hit RETURN to accept the defaults for most of them, except for:
|
||||
This command prompts you for a number of things, such as the name and version of your application.
|
||||
For now, you can simply hit RETURN to accept the defaults for most of them, with the following exception:
|
||||
|
||||
~~~sh
|
||||
entry point: (index.js)
|
||||
~~~
|
||||
|
||||
Enter `app.js` or whatever you want the name of the main file to be. If you want it to be `index.js`, hit RETURN to accept the suggested default file name.
|
||||
Enter `app.js`, or whatever you want the name of the main file to be. If you want it to be `index.js`, hit RETURN to accept the suggested default file name.
|
||||
|
||||
Now install Express in the app directory and save it in the dependencies list:
|
||||
Now install Express in the `app` directory and save it in the dependencies list. For example:
|
||||
|
||||
~~~sh
|
||||
$ npm install express --save
|
||||
~~~
|
||||
|
||||
To install Express temporarily, and not add it to the dependencies list, omit the `--save` option:
|
||||
To install Express temporarily and not add it to the dependencies list, omit the `--save` option:
|
||||
|
||||
~~~sh
|
||||
$ npm install express
|
||||
@@ -45,5 +44,5 @@ $ npm install express
|
||||
|
||||
<div class="doc-box doc-info" markdown="1">
|
||||
Node modules installed with the `--save` option are added to the `dependencies` list in the `package.json` file.
|
||||
Then using `npm install` in the app directory will automatically install modules in the dependencies list.
|
||||
Afterwards, running `npm install` in the `app` directory will automatically install modules in the dependencies list.
|
||||
</div>
|
||||
|
||||
18
starter/static-files.md
Normal file → Executable file
18
starter/static-files.md
Normal file → Executable file
@@ -7,15 +7,15 @@ lang: en
|
||||
|
||||
# Serving static files in Express
|
||||
|
||||
Serving files, such as images, CSS, JavaScript and other static files is accomplished with the help of a built-in middleware in Express - `express.static`.
|
||||
To serve static files such as images, CSS files, and JavaScript files, use the `express.static` built-in middleware function in Express.
|
||||
|
||||
Pass the name of the directory, which is to be marked as the location of static assets, to the `express.static` middleware to start serving the files directly. For example, if you keep your images, CSS, and JavaScript files in a directory named `public`, you can do this:
|
||||
Pass the name of the directory that contains the static assets to the `express.static` middleware function to start serving the files directly. For example, if you keep your images, CSS files, and JavaScript files in a directory named `public`, you can use the following code:
|
||||
|
||||
~~~js
|
||||
app.use(express.static('public'));
|
||||
~~~
|
||||
|
||||
Now, you will be able to load the files under the `public` directory:
|
||||
Now, you can load the files that are in the `public` directory:
|
||||
|
||||
~~~js
|
||||
http://localhost:3000/images/kitten.jpg
|
||||
@@ -26,25 +26,25 @@ http://localhost:3000/hello.html
|
||||
~~~
|
||||
|
||||
<div class="doc-box doc-info">
|
||||
The files are looked up relative to the static directory, therefore, the name of the static directory is not a part of the URL.
|
||||
The files are looked up relative to the static directory, so the name of the static directory is not part of the URL.
|
||||
</div>
|
||||
|
||||
If you want to use multiple directories as static assets directories, you can call the `express.static` middleware multiple times:
|
||||
If you want to use multiple directories as static assets directories, you can call the `express.static` middleware function multiple times:
|
||||
|
||||
~~~js
|
||||
app.use(express.static('public'));
|
||||
app.use(express.static('files'));
|
||||
~~~
|
||||
|
||||
The files will be looked up in the order the static directories were set using the `express.static` middleware.
|
||||
The files are looked up in the order in which you set the static directories by using the `express.static` middleware function.
|
||||
|
||||
If you want to create a "virtual" (since the path does not actually exist in the file system) path prefix for the files served by `express.static`, you can [specify a mount path](/4x/api.html#app.use) for the static directory, as shown below:
|
||||
If you want to create a virtual path prefix (where the path does not actually exist in the file system) for the files that are served by the `express.static` function, you can [specify a mount path](/4x/api.html#app.use) for the static directory, as shown below:
|
||||
|
||||
~~~js
|
||||
app.use('/static', express.static('public'));
|
||||
~~~
|
||||
|
||||
Now, you will be able to load the files under the `public` directory, from the path prefix "/static".
|
||||
Now, you can load the files that are in the `public` directory from the `/static` path prefix.
|
||||
|
||||
~~~js
|
||||
http://localhost:3000/static/images/kitten.jpg
|
||||
@@ -54,7 +54,7 @@ http://localhost:3000/static/images/bg.png
|
||||
http://localhost:3000/static/hello.html
|
||||
~~~
|
||||
|
||||
However, the path you provide to `express.static` is relative to the directory where you launch your node process. If you run the express app from another directory, it's safer to use the absolute path of the directory you want to serve:
|
||||
However, the path that you provide to the `express.static` function is relative to the directory from where you launch your `node` process. If you run the express app from another directory, it's safer to use the absolute path of the directory that you want to serve:
|
||||
|
||||
~~~js
|
||||
app.use('/static', express.static(__dirname + '/public'));
|
||||
|
||||
Reference in New Issue
Block a user