Updates for translation handoff

This commit is contained in:
crandmck
2015-11-21 13:06:24 -08:00
parent 0d2667bafe
commit b9359b2f13
28 changed files with 409 additions and 329 deletions

View File

@@ -97,6 +97,11 @@
</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>

View File

@@ -1,8 +1,10 @@
---
### TRANSLATE ONLY "title" CONTENT IN THIS SECTION
layout: page
title: Performance Best Practices Using Express in Production
menu: advanced
lang: en
### END HEADER BLOCK - BEGIN GENERAL TRANSLATION
---
# Production best practices: performance and reliability
@@ -32,12 +34,12 @@ Here are some things you can do in your code to improve your application's perfo
Gzip compressing can greatly decrease the size of the response body and hence increase the speed of a web app. Use the [compression](https://www.npmjs.com/package/compression) middleware for gzip compression in your Express app. For example:
~~~js
<pre><code class="language-javascript" translate="no">
var compression = require('compression');
var express = require('express');
var app = express();
app.use(compression());
~~~
</code></pre>
For a high-traffic website in production, the best way to put compression in place is to implement it at a reverse proxy level (see [Use a reverse proxy](#proxy)). In that case, you do not need to use compression middleware. For details on enabling gzip compression in Nginx, see [Module ngx_http_gzip_module](http://nginx.org/en/docs/http/ngx_http_gzip_module.html) in the Nginx documentation.
@@ -106,7 +108,7 @@ Use a tool such as [JSHint](http://jshint.com/) or [JSLint](http://www.jslint.co
Here is an example of using try-catch to handle a potential process-crashing exception.
This middleware function accepts a query field parameter named "params" that is a JSON object.
~~~js
<pre><code class="language-javascript" translate="no">
app.get('/search', function (req, res) {
// Simulating async operation
setImmediate(function () {
@@ -119,7 +121,7 @@ app.get('/search', function (req, res) {
}
})
});
~~~
</code></pre>
However, try-catch works only for synchronous code. Since the Node platform is primarily asynchronous (particularly in a production environment), try-catch won't catch a lot of exceptions.
@@ -129,7 +131,7 @@ However, try-catch works only for synchronous code. Since the Node platform is p
Promises will handle any exceptions (both explicit and implicit) in asynchronous code blocks using `then()`. Just add `.catch(next)` to the end of promise chains. For example:
~~~js
<pre><code class="language-javascript" translate="no">
app.get('/', function (req, res, next) {
// do some sync stuff
queryDb()
@@ -146,7 +148,7 @@ app.get('/', function (req, res, next) {
app.use(function (err, req, res, next) {
// handle error
})
~~~
</code></pre>
Now all errors asynchronous and synchronous get propagated to the error middleware.
@@ -155,13 +157,13 @@ However, there are two caveats:
1. All your asynchronous code must return promises (except emitters). If a particular library does not return promises, convert the base object using a helper function like [Bluebird.promisifyAll()](http://bluebirdjs.com/docs/api/promise.promisifyall.html).
2. Event emitters (like streams) can still cause uncaught exceptions. So make sure you are handling the error event properly; for example:
~~~js
<pre><code class="language-javascript" translate="no">
app.get('/', wrap(async (req, res, next) => {
let company = await getCompanyById(req.query.id)
let stream = getLogoStreamById(company.id)
stream.on('error', next).pipe(res)
}))
~~~
</code></pre>
For more information about error-handling using promises, see:
@@ -199,19 +201,19 @@ In development, you typically set environment variables in your interactive shel
With Upstart, use the `env` keyword in your job file. For example:
~~~
</code></pre>
# /etc/init/env.conf
env NODE_ENV=production
~~~
</code></pre>
For more information, see the [Upstart Intro, Cookbook and Best Practices](http://upstart.ubuntu.com/cookbook/#environment-variables).
With systemd, use the `Environment` directive in your unit file. For example:
~~~
</code></pre>
# /etc/systemd/system/myservice.service
Environment=NODE_ENV=production
~~~
</code></pre>
For more information, see [Using Environment Variables In systemd Units](https://coreos.com/os/docs/latest/using-environment-variables-in-systemd-units.html).
@@ -272,7 +274,7 @@ Systemd is a Linux system and service manager. Most major Linux distributions ha
A systemd service configuration file is called a _unit file_, with a filename ending in .service. Here's an example unit file to manage a Node app directly (replace the bolded text with values for your system and app):
~~~
</code></pre>
[Unit]
Description=Awesome Express App
@@ -300,7 +302,7 @@ Restart=always
[Install]
WantedBy=multi-user.target
~~~
</code></pre>
For more information on systemd, see the [systemd reference (man page)](http://www.freedesktop.org/software/systemd/man/systemd.unit.html).
##### StrongLoop PM as a systemd service
@@ -309,15 +311,15 @@ You can easily install StrongLoop Process Manager as a systemd service. After yo
To install StrongLoop PM as a systemd service:
~~~sh
<pre><code class="language-sh" translate="no">
$ sudo sl-pm-install --systemd
~~~
</code></pre>
Then start the service with:
~~~sh
<pre><code class="language-sh" translate="no">
$ sudo /usr/bin/systemctl start strong-pm
~~~
</code></pre>
For more information, see [Setting up a production host (StrongLoop documentation)](https://docs.strongloop.com/display/SLC/Setting+up+a+production+host#Settingupaproductionhost-RHEL7+,Ubuntu15.04or15.10).
@@ -329,7 +331,7 @@ An Upstart service is defined in a job configuration file (also called a "job")
Create a file named `myapp.conf` at `/etc/init/` with the following content (replace the bolded text with values for your system and app):
~~~
</code></pre>
# When to start the process
start on runlevel [2345]
@@ -357,7 +359,7 @@ respawn
# Limit restart attempt to 10 times within 10 seconds
respawn limit 10 10
~~~
</code></pre>
NOTE: This script requires Upstart 1.4 or newer, supported on Ubuntu 12.04-14.10.
@@ -377,15 +379,15 @@ You can easily install StrongLoop Process Manager as an Upstart service. After y
To install StrongLoop PM as an Upstart 1.4 service:
~~~sh
<pre><code class="language-sh" translate="no">
$ sudo sl-pm-install
~~~
</code></pre>
Then run the service with:
~~~sh
<pre><code class="language-sh" translate="no">
$ sudo /sbin/initctl start strong-pm
~~~
</code></pre>
NOTE: On systems that don't support Upstart 1.4, the commands are slightly different. See [Setting up a production host (StrongLoop documentation)](https://docs.strongloop.com/display/SLC/Setting+up+a+production+host#Settingupaproductionhost-RHELLinux5and6,Ubuntu10.04-.10,11.04-.10) for more information.
@@ -411,9 +413,9 @@ When StrongLoop Process Manager (PM) runs an application, it automatically runs
For example, assuming you've deployed your app to prod.foo.com and StrongLoop PM is listening on port 8701 (the default), then to set the cluster size to eight using slc:
~~~sh
<pre><code class="language-sh" translate="no">
$ slc ctl -C http://prod.foo.com:8701 set-size my-app 8
~~~
</code></pre>
For more information on clustering with StrongLoop PM, see [Clustering](https://docs.strongloop.com/display/SLC/Clustering) in StrongLoop documentation.

View File

@@ -1,8 +1,10 @@
---
### TRANSLATE ONLY "title" CONTENT IN THIS SECTION
layout: page
title: Security Best Practices for Express in Production
menu: advanced
lang: en
### END HEADER BLOCK - BEGIN GENERAL TRANSLATION
---
# Production Best Practices: Security
@@ -47,18 +49,18 @@ Helmet is actually just a collection of nine smaller middleware functions that s
Install Helmet like any other module:
~~~sh
<pre><code class="language-sh" translate="no">
$ npm install --save helmet
~~~
</code></pre>
Then to use it in your code:
~~~js
<pre><code class="language-javascript" translate="no">
...
var helmet = require('helmet');
app.use(helmet());
...
~~~
</code></pre>
### At a minimum, disable X-Powered-By header
@@ -66,9 +68,9 @@ If you don't want to use Helmet, then at least disable the `X-Powered-By` header
So, best practice is to to turn off the header with the `app.disable()` method:
~~~js
<pre><code class="language-javascript" translate="no">
app.disable('x-powered-by');
~~~
</code></pre>
If you use `helmet.js`, it takes care of this for you.
@@ -91,7 +93,7 @@ Using the default session cookie name can open your app to attacks. The securit
To avoid this, use generic cookie names; for example using [express-session](https://www.npmjs.com/package/express-session) middleware:
~~~js
<pre><code class="language-javascript" translate="no">
var session = require('express-session');
app.set('trust proxy', 1) // trust first proxy
app.use( session({
@@ -99,7 +101,7 @@ app.use( session({
name : 'sessionId',
})
);
~~~
</code></pre>
### Set cookie security options
@@ -113,7 +115,7 @@ Set the following cookie options to enhance security:
Here is an example using [cookie-session](https://www.npmjs.com/package/cookie-session) middleware:
~~~js
<pre><code class="language-javascript" translate="no">
var session = require('cookie-session');
var express = require('express');
var app = express();
@@ -130,7 +132,7 @@ app.use(session({
}
})
);
~~~
</code></pre>
## Ensure your dependencies are secure
@@ -140,29 +142,29 @@ Use either or both of the following two tools to help ensure security of third-p
[nsp](https://www.npmjs.com/package/nsp) is a command-line tool that checks the [Node Security Project](https://nodesecurity.io/) vulnerability database to determine if your application uses packages with known vulnerabilities. Install it as follows:
~~~sh
<pre><code class="language-sh" translate="no">
$ npm i nsp -g
~~~
</code></pre>
Use this command to submit the `npm-shrinkwrap.json` file for validation to [nodesecurity.io](https://nodesecurity.io/):
~~~sh
<pre><code class="language-sh" translate="no">
$ nsp audit-shrinkwrap
~~~
</code></pre>
Use this command to submit the `package.json` file for validation to [nodesecurity.io](https://nodesecurity.io/):
~~~sh
<pre><code class="language-sh" translate="no">
$ nsp audit-package
~~~
</code></pre>
Here's how to use [requireSafe](https://requiresafe.com/) to audit your Node modules:
~~~sh
<pre><code class="language-sh" translate="no">
$ npm install -g requiresafe
$ cd your-app
$ requiresafe check
~~~
</code></pre>
## Additional considerations

View File

@@ -1,8 +1,10 @@
---
### TRANSLATE ONLY "title" CONTENT IN THIS SECTION
layout: page
title: Developing template engines for Express
menu: advanced
lang: en
### END HEADER BLOCK - BEGIN GENERAL TRANSLATION
---
# Developing template engines for Express
@@ -11,7 +13,7 @@ Use the `app.engine(ext, callback)` method to create your own template engine. `
The following code is an example of implementing a very simple template engine for rendering `.ntl` files.
~~~js
<pre><code class="language-javascript" translate="no">
var fs = require('fs'); // this engine requires the fs module
app.engine('ntl', function (filePath, options, callback) { // define the template engine
fs.readFile(filePath, function (err, content) {
@@ -24,19 +26,19 @@ app.engine('ntl', function (filePath, options, callback) { // define the templat
});
app.set('views', './views'); // specify the views directory
app.set('view engine', 'ntl'); // register the template engine
~~~
</code></pre>
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
<pre><code class="language-javascript" translate="no">
#title#
#message#
~~~
</code></pre>
Then, create the following route in your app.
~~~js
<pre><code class="language-javascript" translate="no">
app.get('/', function (req, res) {
res.render('index', { title: 'Hey', message: 'Hello there!'});
})
~~~
</code></pre>
When you make a request to the home page, `index.ntl` will be rendered as HTML.

View File

@@ -1,8 +1,10 @@
---
### TRANSLATE ONLY "title" CONTENT IN THIS SECTION
layout: page
title: Process managers for Express apps
menu: advanced
lang: en
### END HEADER BLOCK - BEGIN GENERAL TRANSLATION
---
# Process managers for Express apps
@@ -51,19 +53,19 @@ Full documentation:
- [Using StrongLoop Process Manager](http://docs.strongloop.com/display/SLC/Using+Process+Manager).
### Installation
~~~sh
<pre><code class="language-sh" translate="no">
$ [sudo] npm install -g strongloop
~~~
</code></pre>
### Basic use
~~~sh
<pre><code class="language-sh" translate="no">
$ cd my-app
$ slc start
~~~
</code></pre>
View the status of Process Manager and all deployed apps:
~~~sh
<pre><code class="language-sh" translate="no">
$ slc ctl
Service ID: 1
Service Name: my-app
@@ -79,39 +81,39 @@ Processes:
1.1.57694 57694 2 0.0.0.0:3001
1.1.57695 57695 3 0.0.0.0:3001
1.1.57696 57696 4 0.0.0.0:3001
~~~
</code></pre>
List all the apps (services) under management:
~~~sh
<pre><code class="language-sh" translate="no">
$ slc ctl ls
Id Name Scale
1 my-app 1
~~~
</code></pre>
Stop an app:
~~~sh
<pre><code class="language-sh" translate="no">
$ slc ctl stop my-app
~~~
</code></pre>
Restart an app:
~~~sh
<pre><code class="language-sh" translate="no">
$ slc ctl restart my-app
~~~
</code></pre>
You can also "soft restart," which gives worker processes a grace period to close existing connections, then restarts the current application:
~~~sh
<pre><code class="language-sh" translate="no">
$ slc ctl soft-restart my-app
~~~
</code></pre>
To remove an app from management:
~~~sh
<pre><code class="language-sh" translate="no">
$ slc ctl remove my-app
~~~
</code></pre>
## <a id="pm2">PM2</a>
@@ -121,15 +123,15 @@ For more information, see [https://github.com/Unitech/pm2](https://github.com/Un
### Installation
~~~sh
<pre><code class="language-sh" translate="no">
$ [sudo] npm install pm2 -g
~~~
</code></pre>
### Basic use
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
<pre><code class="language-sh" translate="no">
$ pm2 start app.js
[PM2] restartProcessId process id 0
┌──────────┬────┬──────┬───────┬────────┬─────────┬────────┬─────────────┬──────────┐
@@ -138,7 +140,7 @@ $ pm2 start app.js
│ my-app │ 0 │ fork │ 64029 │ online │ 1 │ 0s │ 17.816 MB │ disabled │
└──────────┴────┴──────┴───────┴────────┴─────────┴────────┴─────────────┴──────────┘
Use the `pm2 show <id|name>` command to get more details about an app.
~~~
</code></pre>
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.
@@ -148,33 +150,33 @@ Note that if more than one app with the same name is running, `pm2` commands aff
List all running processes:
~~~sh
<pre><code class="language-sh" translate="no">
$ pm2 list
~~~
</code></pre>
Stop an app:
~~~sh
<pre><code class="language-sh" translate="no">
$ pm2 stop 0
~~~
</code></pre>
Restart an app:
~~~sh
<pre><code class="language-sh" translate="no">
$ pm2 restart 0
~~~
</code></pre>
To view detailed information about an app:
~~~sh
<pre><code class="language-sh" translate="no">
$ pm2 show 0
~~~
</code></pre>
To remove an app from PM2's registry:
~~~sh
<pre><code class="language-sh" translate="no">
$ pm2 delete 0
~~~
</code></pre>
## <a id="forever">Forever</a>
@@ -185,54 +187,54 @@ For more information, see [https://github.com/foreverjs/forever](https://github.
### Installation
~~~sh
<pre><code class="language-sh" translate="no">
$ [sudo] npm install forever -g
~~~
</code></pre>
### Basic use
To start a script, use the `forever start` command and specify the path of the script:
~~~sh
<pre><code class="language-sh" translate="no">
$ forever start script.js
~~~
</code></pre>
This command will run the script in daemon mode (in the background).
To run the script so that it is attached to the terminal, omit `start`:
~~~sh
<pre><code class="language-sh" translate="no">
$ forever script.js
~~~
</code></pre>
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
<pre><code class="language-sh" translate="no">
$ forever start -l forever.log -o out.log -e err.log script.js
~~~
</code></pre>
To view the list of scripts that were started by Forever:
~~~sh
<pre><code class="language-sh" translate="no">
$ forever list
~~~
</code></pre>
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
<pre><code class="language-sh" translate="no">
$ forever stop 1
~~~
</code></pre>
Alternatively, specify the path of the file:
~~~sh
<pre><code class="language-sh" translate="no">
$ forever stop script.js
~~~
</code></pre>
To stop all the scripts that were started by Forever:
~~~sh
<pre><code class="language-sh" translate="no">
$ forever stopall
~~~
</code></pre>
Forever has many more options, and it also provides a programmatic API.

View File

@@ -1,8 +1,10 @@
---
### TRANSLATE ONLY "title" CONTENT IN THIS SECTION
layout: page
title: Express security updates
menu: advanced
lang: en
### END HEADER BLOCK - BEGIN GENERAL TRANSLATION
---
# Security updates

View File

@@ -1,8 +1,10 @@
---
### TRANSLATE ONLY "title" CONTENT IN THIS SECTION
layout: page
title: Express behind proxies
menu: guide
lang: en
### END HEADER BLOCK - BEGIN GENERAL TRANSLATION
---
# Express behind proxies

View File

@@ -1,8 +1,10 @@
---
### TRANSLATE ONLY "title" CONTENT IN THIS SECTION
layout: page
title: Express database integration
menu: guide
lang: en
### END HEADER BLOCK - BEGIN GENERAL TRANSLATION
---
# Database integration
@@ -32,13 +34,13 @@ search on the [npm](https://www.npmjs.com/) site.
**Module**: [cassandra-driver](https://github.com/datastax/nodejs-driver)
**Installation**
~~~sh
<pre><code class="language-sh" translate="no">
$ npm install cassandra-driver
~~~
</code></pre>
**Example**
~~~js
<pre><code class="language-javascript" translate="no">
var cassandra = require('cassandra-driver');
var client = new cassandra.Client({ contactPoints: ['localhost']});
@@ -46,7 +48,7 @@ client.execute('select key from system.local', function(err, result) {
if (err) throw err;
console.log(result.rows[0]);
});
~~~
</code></pre>
<a name="couchdb"></a>
@@ -55,13 +57,13 @@ client.execute('select key from system.local', function(err, result) {
**Module**: [nano](https://github.com/dscape/nano)
**Installation**
~~~sh
<pre><code class="language-sh" translate="no">
$ npm install nano
~~~
</code></pre>
**Example**
~~~js
<pre><code class="language-javascript" translate="no">
var nano = require('nano')('http://localhost:5984');
nano.db.create('books');
var books = nano.db.use('books');
@@ -77,7 +79,7 @@ books.insert({name: 'The Art of war'}, null, function(err, body) {
books.list(function(err, body){
console.log(body.rows);
}
~~~
</code></pre>
<a name="leveldb"></a>
@@ -86,13 +88,13 @@ books.list(function(err, body){
**Module**: [levelup](https://github.com/rvagg/node-levelup)
**Installation**
~~~sh
<pre><code class="language-sh" translate="no">
$ npm install level levelup leveldown
~~~
</code></pre>
**Example**
~~~js
<pre><code class="language-javascript" translate="no">
var levelup = require('levelup');
var db = levelup('./mydb');
@@ -105,7 +107,7 @@ db.put('name', 'LevelUP', function (err) {
});
});
~~~
</code></pre>
<a name="mysql"></a>
@@ -114,13 +116,13 @@ db.put('name', 'LevelUP', function (err) {
**Module**: [mysql](https://github.com/felixge/node-mysql/)
**Installation**
~~~sh
<pre><code class="language-sh" translate="no">
$ npm install mysql
~~~
</code></pre>
**Example**
~~~js
<pre><code class="language-javascript" translate="no">
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
@@ -136,7 +138,7 @@ connection.query('SELECT 1 + 1 AS solution', function(err, rows, fields) {
});
connection.end();
~~~
</code></pre>
<a name="mongo"></a>
@@ -145,13 +147,13 @@ connection.end();
**Module**: [mongodb](https://github.com/mongodb/node-mongodb-native)
**Installation**
~~~sh
<pre><code class="language-sh" translate="no">
$ npm install mongodb
~~~
</code></pre>
**Example**
~~~js
<pre><code class="language-javascript" translate="no">
var MongoClient = require('mongodb').MongoClient;
MongoClient.connect('mongodb://localhost:27017/animals', function(err, db) {
@@ -165,7 +167,7 @@ MongoClient.connect('mongodb://localhost:27017/animals', function(err, db) {
console.log(result);
});
});
~~~
</code></pre>
If you want an object model driver for MongoDB, look at [Mongoose](https://github.com/LearnBoost/mongoose).
@@ -176,13 +178,13 @@ If you want an object model driver for MongoDB, look at [Mongoose](https://githu
**Module**: [apoc](https://github.com/hacksparrow/apoc)
**Installation**
~~~sh
<pre><code class="language-sh" translate="no">
$ npm install apoc
~~~
</code></pre>
**Example**
~~~js
<pre><code class="language-javascript" translate="no">
var apoc = require('apoc');
apoc.query('match (n) return n').exec().then(
@@ -193,7 +195,7 @@ apoc.query('match (n) return n').exec().then(
console.log(fail);
}
);
~~~
</code></pre>
<a name="postgres"></a>
@@ -202,13 +204,13 @@ apoc.query('match (n) return n').exec().then(
**Module**: [pg](https://github.com/brianc/node-postgres)
**Installation**
~~~sh
<pre><code class="language-sh" translate="no">
$ npm install pg
~~~
</code></pre>
**Example**
~~~js
<pre><code class="language-javascript" translate="no">
var pg = require('pg');
var conString = "postgres://username:password@localhost/database";
@@ -226,7 +228,7 @@ pg.connect(conString, function(err, client, done) {
});
});
~~~
</code></pre>
<a name="redis"></a>
@@ -235,13 +237,13 @@ pg.connect(conString, function(err, client, done) {
**Module**: [redis](https://github.com/mranney/node_redis)
**Installation**
~~~sh
<pre><code class="language-sh" translate="no">
$ npm install redis
~~~
</code></pre>
**Example**
~~~js
<pre><code class="language-javascript" translate="no">
var client = require('redis').createClient();
client.on('error', function (err) {
@@ -262,7 +264,7 @@ client.hkeys('hash key', function (err, replies) {
client.quit();
});
~~~
</code></pre>
<a name="sqlite"></a>
@@ -271,13 +273,13 @@ client.hkeys('hash key', function (err, replies) {
**Module**: [sqlite3](https://github.com/mapbox/node-sqlite3)
**Installation**
~~~sh
<pre><code class="language-sh" translate="no">
$ npm install sqlite3
~~~
</code></pre>
**Example**
~~~js
<pre><code class="language-javascript" translate="no">
var sqlite3 = require('sqlite3').verbose();
var db = new sqlite3.Database(':memory:');
@@ -298,7 +300,7 @@ db.serialize(function() {
});
db.close();
~~~
</code></pre>
<a name="elasticsearch"></a>
@@ -307,13 +309,13 @@ db.close();
**Module**: [elasticsearch](https://github.com/elastic/elasticsearch-js)
**Installation**
~~~sh
<pre><code class="language-sh" translate="no">
$ npm install elasticsearch
~~~
</code></pre>
**Example**
~~~js
<pre><code class="language-javascript" translate="no">
var elasticsearch = require('elasticsearch');
var client = elasticsearch.Client({
host: 'localhost:9200'
@@ -335,4 +337,4 @@ client.search({
}, function(error) {
console.trace(error.message);
});
~~~
</code></pre>

View File

@@ -1,8 +1,10 @@
---
### TRANSLATE ONLY "title" CONTENT IN THIS SECTION
layout: page
title: Debugging Express
menu: guide
lang: en
### END HEADER BLOCK - BEGIN GENERAL TRANSLATION
---
# Debugging Express
@@ -19,19 +21,19 @@ comment out `debug` logs in production code. Logging is turned off by default an
To see all the internal logs used in Express, set the `DEBUG` environment variable to
`express:*` when launching your app.
~~~sh
<pre><code class="language-sh" translate="no">
$ DEBUG=express:* node index.js
~~~
</code></pre>
On Windows, use the corresponding command.
~~~sh
<pre><code class="language-sh" translate="no">
> set DEBUG=express:* & node index.js
~~~
</code></pre>
Running this command on the default app generated by the [express generator](/starter/generator.html) prints the following output:
~~~sh
<pre><code class="language-sh" translate="no">
$ DEBUG=express:* node ./bin/www
express:router:route new / +0ms
express:router:layer new / +1ms
@@ -73,11 +75,11 @@ $ DEBUG=express:* node ./bin/www
express:router:layer new / +0ms
express:router use / <anonymous> +0ms
express:router:layer new / +0ms
~~~
</code></pre>
When a request is then made to the app, you will see the logs specified in the Express code:
~~~sh
<pre><code class="language-sh" translate="no">
express:router dispatching GET / +4h
express:router query : / +2ms
express:router expressInit : / +0ms
@@ -93,7 +95,7 @@ When a request is then made to the app, you will see the logs specified in the E
express:view lookup "index.jade" +338ms
express:view stat "/projects/example/views/index.jade" +0ms
express:view render "/projects/example/views/index.jade" +1ms
~~~
</code></pre>
To see the logs only from the router implementation set the value of `DEBUG` to `express:router`. Likewise, to see logs only from the application implementation set the value of `DEBUG` to `express:application`, and so on.
@@ -103,14 +105,14 @@ The app generated by the `express` command also uses the `debug` module and its
If you generated the app with `$ express sample-app`, you can enable the debug statements with the following command:
~~~sh
<pre><code class="language-sh" translate="no">
$ DEBUG=sample-app node ./bin/www
~~~
</code></pre>
You can specify more than one debug namespace by assigning a comma separated list of names:
~~~sh
<pre><code class="language-sh" translate="no">
$ DEBUG=http,mail,express:* node index.js
~~~
</code></pre>
For more documentation about `debug`, see the [debug guide](https://github.com/visionmedia/debug).

View File

@@ -1,8 +1,10 @@
---
### TRANSLATE ONLY "title" CONTENT IN THIS SECTION
layout: page
title: Express error handling
menu: guide
lang: en
### END HEADER BLOCK - BEGIN GENERAL TRANSLATION
---
# Error handling
@@ -11,16 +13,16 @@ Define error-handling middleware functions in the same way as other middleware f
except error-handling functions have four arguments instead of three:
`(err, req, res, next)`. For example:
~~~js
<pre><code class="language-javascript" translate="no">
app.use(function(err, req, res, next) {
console.error(err.stack);
res.status(500).send('Something broke!');
});
~~~
</code></pre>
You define error-handling middleware last, after other `app.use()` and routes calls; for example:
~~~js
<pre><code class="language-javascript" translate="no">
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
@@ -29,7 +31,7 @@ app.use(methodOverride());
app.use(function(err, req, res, next) {
// logic
});
~~~
</code></pre>
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.
@@ -38,7 +40,7 @@ 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
<pre><code class="language-javascript" translate="no">
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
@@ -47,21 +49,21 @@ app.use(methodOverride());
app.use(logErrors);
app.use(clientErrorHandler);
app.use(errorHandler);
~~~
</code></pre>
In this example, the generic `logErrors` might write request and
error information to `stderr`, for example:
~~~js
<pre><code class="language-javascript" translate="no">
function logErrors(err, req, res, next) {
console.error(err.stack);
next(err);
}
~~~
</code></pre>
Also in this example, `clientErrorHandler` is defined as follows; in this case, the error is explicitly passed along to the next one:
~~~js
<pre><code class="language-javascript" translate="no">
function clientErrorHandler(err, req, res, next) {
if (req.xhr) {
res.status(500).send({ error: 'Something failed!' });
@@ -69,22 +71,22 @@ function clientErrorHandler(err, req, res, next) {
next(err);
}
}
~~~
</code></pre>
The "catch-all" `errorHandler` function might be implemented as follows:
~~~js
<pre><code class="language-javascript" translate="no">
function errorHandler(err, req, res, next) {
res.status(500);
res.render('error', { error: err });
}
~~~
</code></pre>
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:
~~~js
<pre><code class="language-javascript" translate="no">
app.get('/a_route_behind_paywall',
function checkIfPaidSubscriber(req, res, next) {
if(!req.user.hasPaid) {
@@ -98,7 +100,7 @@ app.get('/a_route_behind_paywall',
res.json(doc);
});
});
~~~
</code></pre>
In this example, the `getPaidContent` handler will be skipped but any remaining handlers in `app` for `/a_route_behind_paywall` would continue to be executed.
@@ -127,7 +129,7 @@ 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
<pre><code class="language-javascript" translate="no">
function errorHandler(err, req, res, next) {
if (res.headersSent) {
return next(err);
@@ -135,4 +137,4 @@ function errorHandler(err, req, res, next) {
res.status(500);
res.render('error', { error: err });
}
~~~
</code></pre>

View File

@@ -1,8 +1,10 @@
---
### TRANSLATE ONLY "title" CONTENT IN THIS SECTION
layout: page
title: Migrating to Express 4
menu: guide
lang: en
### END HEADER BLOCK - BEGIN GENERAL TRANSLATION
---
# Moving to Express 4
@@ -99,12 +101,12 @@ GitHub.
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
<pre><code class="language-javascript" translate="no">
app.use('/book/:id', function(req, res, next) {
console.log('ID:', req.params.id);
next();
});
~~~
</code></pre>
<h3 id="routing">
The routing system
</h3>
@@ -128,7 +130,7 @@ information about routes, see [`Router()` documentation](/4x/api.html#router).
Here is an example of chained route handlers that are defined by using the `app.route()` function.
~~~js
<pre><code class="language-javascript" translate="no">
app.route('/book')
.get(function(req, res) {
res.send('Get a random book');
@@ -139,7 +141,7 @@ app.route('/book')
.put(function(req, res) {
res.send('Update the book');
});
~~~
</code></pre>
<h4 id="express-router"><code>express.Router</code> class</h4>
@@ -154,7 +156,7 @@ it, defines some routes, and mounts it on a path on the main app.
For example, create a router file named `birds.js` in the app directory,
with the following content:
~~~js
<pre><code class="language-javascript" translate="no">
var express = require('express');
var router = express.Router();
@@ -173,15 +175,15 @@ router.get('/about', function(req, res) {
});
module.exports = router;
~~~
</code></pre>
Then, load the router module in the app:
~~~js
<pre><code class="language-javascript" translate="no">
var birds = require('./birds');
...
app.use('/birds', birds);
~~~
</code></pre>
The app will now be able to handle requests to the `/birds` and
`/birds/about` paths, and will call the `timeLog`
@@ -319,7 +321,7 @@ Version 3 app
Consider an Express v.3 application with the following `app.js` file:
~~~js
<pre><code class="language-javascript" translate="no">
var express = require('express');
var routes = require('./routes');
var user = require('./routes/user');
@@ -351,14 +353,14 @@ app.get('/users', user.list);
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
~~~
</code></pre>
<h4 id=""><code>package.json</code></h4>
The accompanying version 3 `package.json` file might look
something like this:
~~~js
<pre><code class="language-javascript" translate="no">
{
"name": "application-name",
"version": "0.0.1",
@@ -371,7 +373,7 @@ The accompanying version 3 `package.json` file might look
"jade": "*"
}
}
~~~
</code></pre>
<h3 id="">
Process
@@ -381,9 +383,9 @@ Begin the migration process by installing the required middleware for the
Express 4 app and updating Express and Jade to their respective latest
version with the following command:
~~~sh
<pre><code class="language-sh" translate="no">
$ npm install serve-favicon morgan method-override express-session body-parser multer errorhandler express@latest jade@latest --save
~~~
</code></pre>
Make the following changes to `app.js`:
@@ -406,7 +408,7 @@ Make the following changes to `app.js`:
Running the above `npm` command will update `package.json` as follows:
~~~js
<pre><code class="language-javascript" translate="no">
{
"name": "application-name",
"version": "0.0.1",
@@ -426,14 +428,14 @@ Running the above `npm` command will update `package.json` as follows:
"serve-favicon": "^2.0.1"
}
}
~~~
</code></pre>
<h4 id=""><code>app.js</code></h4>
Then, remove invalid code, load the required middleware, and make other
changes as necessary. The `app.js` file will look like this:
~~~js
<pre><code class="language-javascript" translate="no">
var http = require('http');
var express = require('express');
var routes = require('./routes');
@@ -477,7 +479,7 @@ var server = http.createServer(app);
server.listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
~~~
</code></pre>
<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 simply started this way:
@@ -491,9 +493,9 @@ Unless you need to work directly with the `http` module (socket.io/SPDY/HTTPS),
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
<pre><code class="language-sh" translate="no">
$ node .
~~~
</code></pre>
Load [http://localhost:3000](http://localhost:3000)
and see the home page being rendered by Express 4.
@@ -510,17 +512,17 @@ The command-line tool to generate an Express app is still
If you already have the Express 3 app generator installed on your system,
you must uninstall it:
~~~sh
<pre><code class="language-sh" translate="no">
$ npm uninstall -g express
~~~
</code></pre>
Depending on how your file and directory privileges are configured,
you might need to run this command with `sudo`.
Now install the new generator:
~~~sh
<pre><code class="language-sh" translate="no">
$ npm install -g express-generator
~~~
</code></pre>
Depending on how your file and directory privileges are configured,
you might need to run this command with `sudo`.
@@ -541,9 +543,9 @@ Command options and use largely remain the same, with the following exceptions:
Execute the following command to create an Express 4 app:
~~~sh
<pre><code class="language-sh" translate="no">
$ express app4
~~~
</code></pre>
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
@@ -554,9 +556,9 @@ You will also notice that the `app.js` file is now a Node.js module, in contrast
After installing the dependencies, start the app by using the following command:
~~~sh
<pre><code class="language-sh" translate="no">
$ npm start
~~~
</code></pre>
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
@@ -578,19 +580,19 @@ 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 the
`app.js` file, then paste the following code in its place:
~~~js
<pre><code class="language-javascript" translate="no">
app.set('port', process.env.PORT || 3000);
var server = app.listen(app.get('port'), function() {
debug('Express server listening on port ' + server.address().port);
});
~~~
</code></pre>
Ensure that you load the `debug` module at the top of the `app.js` file by using the following code:
~~~js
<pre><code class="language-javascript" translate="no">
var debug = require('debug')('app4');
~~~
</code></pre>
Next, change `"start": "node ./bin/www"` in the `package.json` file to `"start": "node app.js"`.

View File

@@ -1,8 +1,10 @@
---
### TRANSLATE ONLY "title" CONTENT IN THIS SECTION
layout: page
title: Migrating to Express 5
menu: guide
lang: en
### END HEADER BLOCK - BEGIN GENERAL TRANSLATION
---
# Moving to Express 5
@@ -15,9 +17,9 @@ Express 5 is not very different from Express 4: The changes to the API are not a
To install the latest alpha and to preview Express 5, enter the following command in your application root directory:
~~~sh
<pre><code class="language-sh" translate="no">
$ npm install express@5.0.0-alpha.2 --save
~~~
</code></pre>
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.

View File

@@ -1,8 +1,10 @@
---
### TRANSLATE ONLY "title" CONTENT IN THIS SECTION
layout: page
title: Express routing
menu: guide
lang: en
### END HEADER BLOCK - BEGIN GENERAL TRANSLATION
---
# Routing
@@ -13,7 +15,7 @@ A route is a combination of a URI, an HTTP request method (such as GET and POST)
The following code is an example of a very basic route.
~~~js
<pre><code class="language-javascript" translate="no">
var express = require('express');
var app = express();
@@ -21,7 +23,7 @@ var app = express();
app.get('/', function(req, res) {
res.send('hello world');
});
~~~
</code></pre>
<h2 id="route-methods">Route methods</h2>
@@ -29,7 +31,7 @@ A route method is derived from one of the HTTP methods, and is attached to an in
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
<pre><code class="language-javascript" translate="no">
// GET method route
app.get('/', function (req, res) {
res.send('GET request to the homepage');
@@ -40,7 +42,7 @@ app.post('/', function (req, res) {
res.send('POST request to the homepage');
});
~~~
</code></pre>
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`.
@@ -53,12 +55,12 @@ There is a special routing method, `app.all()`, which is not derived from any HT
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
<pre><code class="language-javascript" translate="no">
app.all('/secret', function (req, res, next) {
console.log('Accessing the secret section ...');
next(); // pass control to the next handler
});
~~~
</code></pre>
<h2 id="route-paths">Route paths</h2>
@@ -72,48 +74,65 @@ Route paths, in combination with a request method, define the endpoints at which
Query strings are not part of the route path.
</div>
Examples of route paths that are based on strings:
Here are some examples of route paths based on strings.
~~~js
// will match a request to the root
This route path will match requests to the root route, `/`.
<pre><code class="language-javascript" translate="no">
app.get('/', function (req, res) {
res.send('root');
});
</code></pre>
// will match requests to /about
This route path will match requests to `/about`.
<pre><code class="language-javascript" translate="no">
app.get('/about', function (req, res) {
res.send('about');
});
</code></pre>
// will match request to /random.text
This route path will match requests to `/random.text`.
<pre><code class="language-javascript" translate="no">
app.get('/random.text', function (req, res) {
res.send('random.text');
});
~~~
</code></pre>
Examples of route paths based on string patterns:
Here are some examples of route paths based on string patterns.
~~~js
// will match acd and abcd
This route path will match `acd` and `abcd`.
<pre><code class="language-javascript" translate="no">
app.get('/ab?cd', function(req, res) {
res.send('ab?cd');
});
</code></pre>
// will match abcd, abbcd, abbbcd, and so on
This route path will match `abcd`, `abbcd`, `abbbcd`, and so on.
<pre><code class="language-javascript" translate="no">
app.get('/ab+cd', function(req, res) {
res.send('ab+cd');
});
</code></pre>
// will match abcd, abxcd, abRABDOMcd, ab123cd, and so on
This route path will match `abcd`, `abxcd`, `abRABDOMcd`, `ab123cd`, and so on.
<pre><code class="language-javascript" translate="no">
app.get('/ab*cd', function(req, res) {
res.send('ab*cd');
});
</code></pre>
// will match /abe and /abcde
This route path will match `/abe` and `/abcde`.
<pre><code class="language-javascript" translate="no">
app.get('/ab(cd)?e', function(req, res) {
res.send('ab(cd)?e');
});
~~~
</code></pre>
<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.
@@ -121,17 +140,21 @@ The characters ?, +, *, and () are subsets of their regular expression counterpa
Examples of route paths based on regular expressions:
~~~js
// will match anything with an "a" in the route name:
This route path will match anything with an "a" in the route name.
<pre><code class="language-javascript" translate="no">
app.get(/a/, function(req, res) {
res.send('/a/');
});
</code></pre>
// will match butterfly and dragonfly; but not butterflyman, dragonfly man, and so on
This route path will match `butterfly` and `dragonfly`, but not `butterflyman`, `dragonfly man`, and so on.
<pre><code class="language-javascript" translate="no">
app.get(/.*fly$/, function(req, res) {
res.send('/.*fly$/');
});
~~~
</code></pre>
<h2 id="route-handlers">Route handlers</h2>
@@ -139,28 +162,28 @@ You can provide multiple callback functions that behave like [middleware](/guide
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:
A single callback function can handle a route. For example:
~~~js
<pre><code class="language-javascript" translate="no">
app.get('/example/a', function (req, res) {
res.send('Hello from A!');
});
~~~
</code></pre>
A route can be handled using more than one callback function (make sure you specify the `next` object):
More than one callback function can handle a route (make sure you specify the `next` object). For example:
~~~js
<pre><code class="language-javascript" translate="no">
app.get('/example/b', function (req, res, next) {
console.log('the response will be sent by the next function ...');
next();
}, function (req, res) {
res.send('Hello from B!');
});
~~~
</code></pre>
A route can be handled using an array of callback functions:
An array of callback functions can handle a route. For example:
~~~js
<pre><code class="language-javascript" translate="no">
var cb0 = function (req, res, next) {
console.log('CB0');
next();
@@ -176,11 +199,11 @@ var cb2 = function (req, res) {
}
app.get('/example/c', [cb0, cb1, cb2]);
~~~
</code></pre>
A route can be handled using a combination of independent functions and arrays of functions:
A combination of independent functions and arrays of functions can handle a route. For example:
~~~js
<pre><code class="language-javascript" translate="no">
var cb0 = function (req, res, next) {
console.log('CB0');
next();
@@ -197,7 +220,7 @@ app.get('/example/d', [cb0, cb1], function (req, res, next) {
}, function (req, res) {
res.send('Hello from D!');
});
~~~
</code></pre>
<h2 id="response-methods">Response methods</h2>
@@ -222,7 +245,7 @@ Because the path is specified at a single location, creating modular routes is h
Here is an example of chained route handlers that are defined by using `app.route()`.
~~~js
<pre><code class="language-javascript" translate="no">
app.route('/book')
.get(function(req, res) {
res.send('Get a random book');
@@ -233,7 +256,7 @@ app.route('/book')
.put(function(req, res) {
res.send('Update the book');
});
~~~
</code></pre>
<h2 id="express-router">express.Router</h2>
@@ -243,7 +266,7 @@ The following example creates a router as a module, loads a middleware function
Create a router file named `birds.js` in the app directory, with the following content:
~~~js
<pre><code class="language-javascript" translate="no">
var express = require('express');
var router = express.Router();
@@ -262,15 +285,15 @@ router.get('/about', function(req, res) {
});
module.exports = router;
~~~
</code></pre>
Then, load the router module in the app:
~~~js
<pre><code class="language-javascript" translate="no">
var birds = require('./birds');
...
app.use('/birds', birds);
~~~
</code></pre>
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.

View File

@@ -1,8 +1,10 @@
---
### TRANSLATE ONLY "title" CONTENT IN THIS SECTION
layout: page
title: Using Express middleware
menu: guide
lang: en
### END HEADER BLOCK - BEGIN GENERAL TRANSLATION
---
# Using middleware
@@ -37,37 +39,37 @@ Bind application-level middleware to an instance of the [app object](/4x/api.htm
This example shows a middleware function with no mount path. The function is executed every time the app receives a request.
~~~js
<pre><code class="language-javascript" translate="no">
var app = express();
app.use(function (req, res, next) {
console.log('Time:', Date.now());
next();
});
~~~
</code></pre>
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
<pre><code class="language-javascript" translate="no">
app.use('/user/:id', function (req, res, next) {
console.log('Request Type:', req.method);
next();
});
~~~
</code></pre>
This example shows a route and its handler function (middleware system). The function handles GET requests to the `/user/:id` path.
~~~js
<pre><code class="language-javascript" translate="no">
app.get('/user/:id', function (req, res, next) {
res.send('USER');
});
~~~
</code></pre>
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
<pre><code class="language-javascript" translate="no">
app.use('/user/:id', function(req, res, next) {
console.log('Request URL:', req.originalUrl);
next();
@@ -75,13 +77,13 @@ app.use('/user/:id', function(req, res, next) {
console.log('Request Type:', req.method);
next();
});
~~~
</code></pre>
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
<pre><code class="language-javascript" translate="no">
app.get('/user/:id', function (req, res, next) {
console.log('ID:', req.params.id);
next();
@@ -93,14 +95,14 @@ app.get('/user/:id', function (req, res, next) {
app.get('/user/:id', function (req, res, next) {
res.end(req.params.id);
});
~~~
</code></pre>
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
<pre><code class="language-javascript" translate="no">
app.get('/user/:id', function (req, res, next) {
// if the user ID is 0, skip to the next route
if (req.params.id == 0) next('route');
@@ -115,20 +117,20 @@ app.get('/user/:id', function (req, res, next) {
app.get('/user/:id', function (req, res, next) {
res.render('special');
});
~~~
</code></pre>
<h2 id='middleware.router'>Router-level middleware</h2>
Router-level middleware works in the same way as application-level middleware, except it is bound to an instance of `express.Router()`.
~~~js
<pre><code class="language-javascript" translate="no">
var router = express.Router();
~~~
</code></pre>
Load router-level middleware by using the `router.use()` and `router.METHOD()` functions.
The following example code replicates the middleware system that is shown above for application-level middleware, by using router-level middleware:
~~~js
<pre><code class="language-javascript" translate="no">
var app = express();
var router = express.Router();
@@ -166,7 +168,7 @@ router.get('/user/:id', function (req, res, next) {
// mount the router on the app
app.use('/', router);
~~~
</code></pre>
<h2 id='middleware.error-handling'>Error-handling middleware</h2>
@@ -176,12 +178,12 @@ Error-handling middleware always takes _four_ arguments. You must provide four
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
<pre><code class="language-javascript" translate="no">
app.use(function(err, req, res, next) {
console.error(err.stack);
res.status(500).send('Something broke!');
});
~~~
</code></pre>
For details about error-handling middleware, see: [Error handling](/guide/error-handling.html).
@@ -211,7 +213,7 @@ The optional `options` object can have the following properties:
Here is an example of using the `express.static` middleware function with an elaborate options object:
~~~js
<pre><code class="language-javascript" translate="no">
var options = {
dotfiles: 'ignore',
etag: false,
@@ -225,15 +227,15 @@ var options = {
}
app.use(express.static('public', options));
~~~
</code></pre>
You can have more than one static directory per app:
~~~js
<pre><code class="language-javascript" translate="no">
app.use(express.static('public'));
app.use(express.static('uploads'));
app.use(express.static('files'));
~~~
</code></pre>
For more details about the `serve-static` function and its options, see: [serve-static](https://github.com/expressjs/serve-static) documentation.
@@ -245,17 +247,17 @@ Install the Node.js module for the required functionality, then load it in your
The following example illustrates installing and loading the cookie-parsing middleware function `cookie-parser`.
~~~sh
<pre><code class="language-sh" translate="no">
$ npm install cookie-parser
~~~
</code></pre>
~~~js
<pre><code class="language-javascript" translate="no">
var express = require('express');
var app = express();
var cookieParser = require('cookie-parser');
// load the cookie-parsing middleware
app.use(cookieParser());
~~~
</code></pre>
For a partial list of third-party middleware functions that are commonly used with Express, see: [Third-party middleware](../resources/middleware.html).

View File

@@ -1,8 +1,10 @@
---
### TRANSLATE ONLY "title" CONTENT IN THIS SECTION
layout: page
title: Using template engines with Express
menu: guide
lang: en
### END HEADER BLOCK - BEGIN GENERAL TRANSLATION
---
# Using template engines with Express
@@ -14,9 +16,9 @@ Before Express can render template files, the following application settings mus
Then install the corresponding template engine npm package:
~~~sh
<pre><code class="language-sh" translate="no">
$ npm install jade --save
~~~
</code></pre>
<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 the `res.render()` function to render the template code.
@@ -26,27 +28,27 @@ Some template engines do not follow this convention. The [Consolidate.js](https:
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
<pre><code class="language-javascript" translate="no">
app.set('view engine', 'jade');
~~~
</code></pre>
Create a Jade template file named `index.jade` in the `views` directory, with the following content:
~~~js
<pre><code class="language-javascript" translate="no">
html
head
title!= title
body
h1!= message
~~~
</code></pre>
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
<pre><code class="language-javascript" translate="no">
app.get('/', function (req, res) {
res.render('index', { title: 'Hey', message: 'Hello there!'});
});
~~~
</code></pre>
When you make a request to the home page, the `index.jade` file will be rendered as HTML.

View File

@@ -1,8 +1,10 @@
---
### TRANSLATE ONLY "title" CONTENT IN THIS SECTION
layout: page
title: Writing middleware for use in Express apps
menu: guide
lang: en
### END HEADER BLOCK - BEGIN GENERAL TRANSLATION
---
# Writing middleware for use in Express apps
@@ -26,7 +28,7 @@ The following figure shows the elements of a middleware function call:
To learn how to write and use Express middleware functions, we will write two middleware functions for the following, simple "Hello world" app:
~~~js
<pre><code class="language-javascript" translate="no">
var express = require('express');
var app = express();
@@ -35,18 +37,18 @@ app.get('/', function (req, res) {
});
app.listen(3000);
~~~
</code></pre>
<h2>Development</h2>
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
<pre><code class="language-javascript" translate="no">
var myLogger = function (req, res, next) {
console.log('LOGGED');
next();
};
~~~
</code></pre>
<div class="doc-box doc-notice" markdown="1">
Notice the call above to `next()`. Calling this function invokes the next middleware function in the app.
@@ -56,7 +58,7 @@ The `next()` function is not a part of the Node.js or Express API, but is the th
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
<pre><code class="language-javascript" translate="no">
var express = require('express');
var app = express();
@@ -72,7 +74,7 @@ app.get('/', function (req, res) {
});
app.listen(3000);
~~~
</code></pre>
Every time the app receives a request, it prints the message "LOGGED" to the terminal.
@@ -84,16 +86,16 @@ The middleware function `myLogger` simply prints a message, then passes on the r
The next example adds a property called `requestTime` to the request object. We'll name this middleware function "requestTime".
~~~js
<pre><code class="language-javascript" translate="no">
var requestTime = function (req, res, next) {
req.requestTime = Date.now();
next();
};
~~~
</code></pre>
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
<pre><code class="language-javascript" translate="no">
var express = require('express');
var app = express();
@@ -111,7 +113,7 @@ app.get('/', function (req, res) {
});
app.listen(3000);
~~~
</code></pre>
When you make a request to the root of the app, the app now displays the timestamp of your request in the browser.

View File

@@ -1,8 +1,10 @@
---
### TRANSLATE ONLY "title" CONTENT IN THIS SECTION
layout: home
title: Express - Node.js web application framework
menu: home
lang: en
### END HEADER BLOCK - BEGIN GENERAL TRANSLATION
---
<section id="home-content">

View File

@@ -1,8 +1,10 @@
---
### TRANSLATE ONLY "title" CONTENT IN THIS SECTION
layout: page
title: Express applications
menu: resources
lang: en
### END HEADER BLOCK - BEGIN GENERAL TRANSLATION
---
# Applications

View File

@@ -1,8 +1,10 @@
---
### TRANSLATE ONLY "title" CONTENT IN THIS SECTION
layout: page
title: Express books and blogs
menu: resources
lang: en
### END HEADER BLOCK - BEGIN GENERAL TRANSLATION
---
# Books and blogs

View File

@@ -1,8 +1,10 @@
---
### TRANSLATE ONLY "title" CONTENT IN THIS SECTION
layout: page
title: Express community
menu: resources
lang: en
### END HEADER BLOCK - BEGIN GENERAL TRANSLATION
---
# Community

View File

@@ -1,8 +1,10 @@
---
### TRANSLATE ONLY "title" CONTENT IN THIS SECTION
layout: page
title: Express glossary
menu: resources
lang: en
### END HEADER BLOCK - BEGIN GENERAL TRANSLATION
---
# Glossary

View File

@@ -1,8 +1,10 @@
---
### TRANSLATE ONLY "title" CONTENT IN THIS SECTION
layout: page
title: Express middleware
menu: resources
lang: en
### END HEADER BLOCK - BEGIN GENERAL TRANSLATION
---
# Third-party middleware

View File

@@ -1,8 +1,10 @@
---
### TRANSLATE ONLY "title" CONTENT IN THIS SECTION
layout: page
title: Express basic routing tutorial
menu: starter
lang: en
### END HEADER BLOCK - BEGIN GENERAL TRANSLATION
---
# Basic routing tutorial
@@ -19,7 +21,7 @@ This tutorial assumes that an instance of `express` named `app` is created and t
The following code illustrates some example routes in an app:
~~~js
<pre><code class="language-javascript" translate="no">
// respond with "Hello World!" on the homepage
app.get('/', function (req, res) {
res.send('Hello World!');
@@ -39,6 +41,6 @@ app.put('/user', function (req, res) {
app.delete('/user', function (req, res) {
res.send('Got a DELETE request at /user');
});
~~~
</code></pre>
For more details about routing, see the [routing guide](/guide/routing.html).

View File

@@ -1,8 +1,10 @@
---
### TRANSLATE ONLY "title" CONTENT IN THIS SECTION
layout: page
title: Express FAQ
menu: starter
lang: en
### END HEADER BLOCK - BEGIN GENERAL TRANSLATION
---
# FAQ
@@ -57,23 +59,23 @@ and found that none of them responded. All you need to
do is add a middleware function at the very bottom of the stack (below all other functions)
to handle a 404 response:
~~~js
<pre><code class="language-javascript" translate="no">
app.use(function(req, res, next) {
res.status(404).send('Sorry cant find that!');
});
~~~
</code></pre>
## How do you setup an error handler?
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
<pre><code class="language-javascript" translate="no">
app.use(function(err, req, res, next) {
console.error(err.stack);
res.status(500).send('Something broke!');
});
~~~
</code></pre>
For more information, see [Error handling](/guide/error-handling.html).

View File

@@ -1,8 +1,10 @@
---
### TRANSLATE ONLY "title" CONTENT IN THIS SECTION
layout: page
title: Express application generator
menu: starter
lang: en
### END HEADER BLOCK - BEGIN GENERAL TRANSLATION
---
# Express application generator
@@ -11,13 +13,13 @@ Use the application generator tool, `express`, to quickly create an application
Install `express` with the following command:
~~~sh
<pre><code class="language-sh" translate="no">
$ npm install express-generator -g
~~~
</code></pre>
Display the command options with the `-h` option:
~~~sh
<pre><code class="language-sh" translate="no">
$ express -h
Usage: express [options] [dir]
@@ -32,11 +34,11 @@ $ express -h
-c, --css <engine> add stylesheet <engine> support (less|stylus|compass|sass) (defaults to plain css)
--git add .gitignore
-f, --force force on non-empty directory
~~~
</code></pre>
For example, the following creates an Express app named _myapp_ in the current working directory:
~~~sh
<pre><code class="language-sh" translate="no">
$ express myapp
create : myapp
@@ -56,32 +58,32 @@ $ express myapp
create : myapp/views/error.jade
create : myapp/bin
create : myapp/bin/www
~~~
</code></pre>
Then install dependencies:
~~~sh
<pre><code class="language-sh" translate="no">
$ cd myapp
$ npm install
~~~
</code></pre>
On MacOS or Linux, run the app with this command:
~~~sh
<pre><code class="language-sh" translate="no">
$ DEBUG=myapp:* npm start
~~~
</code></pre>
On Windows, use this command:
~~~sh
<pre><code class="language-sh" translate="no">
> set DEBUG=myapp:* & npm start
~~~
</code></pre>
Then load `http://localhost:3000/` in your browser to access the app.
The generated app has the following directory structure:
~~~sh
<pre><code class="language-sh" translate="no">
.
├── app.js
├── bin
@@ -101,7 +103,7 @@ The generated app has the following directory structure:
└── layout.jade
7 directories, 9 files
~~~
</code></pre>
<div class="doc-box doc-info" markdown="1">
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.

View File

@@ -1,8 +1,10 @@
---
### TRANSLATE ONLY "title" CONTENT IN THIS SECTION
layout: page
title: Express "Hello World" example
menu: starter
lang: en
### END HEADER BLOCK - BEGIN GENERAL TRANSLATION
---
# Hello world example
@@ -15,7 +17,7 @@ First create a directory named `myapp`, change to it and run `npm init`. Then in
In the `myapp` directory, create a file named `app.js` and add the following code:
~~~js
<pre><code class="language-javascript" translate="no">
var express = require('express');
var app = express();
@@ -29,7 +31,7 @@ var server = app.listen(3000, function () {
console.log('Example app listening at http://%s:%s', host, port);
});
~~~
</code></pre>
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**.
@@ -41,9 +43,9 @@ The `req` (request) and `res` (response) are the exact same objects that Node pr
Run the app with the following command:
~~~ sh
</code></pre> sh
$ node app.js
~~~
</code></pre>
Then, load [http://localhost:3000/](http://localhost:3000/) in a browser to see the output.

View File

@@ -1,46 +1,48 @@
---
### TRANSLATE ONLY "title" CONTENT IN THIS SECTION
layout: page
title: Installing Express
menu: starter
lang: en
### END HEADER BLOCK - BEGIN GENERAL TRANSLATION
---
# Installing
Assuming you've already installed [Node.js](https://nodejs.org/), create a directory to hold your application, and make that your working directory.
~~~sh
<pre><code class="language-sh" translate="no">
$ mkdir myapp
$ cd myapp
~~~
</code></pre>
Use the `npm init` command to create a `package.json` file for your application.
For more information on how `package.json` works, see [Specifics of npm's package.json handling](https://docs.npmjs.com/files/package.json).
~~~sh
<pre><code class="language-sh" translate="no">
$ npm init
~~~
</code></pre>
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
<pre><code class="language-sh" translate="no">
entry point: (index.js)
~~~
</code></pre>
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. For example:
~~~sh
<pre><code class="language-sh" translate="no">
$ npm install express --save
~~~
</code></pre>
To install Express temporarily and not add it to the dependencies list, omit the `--save` option:
~~~sh
<pre><code class="language-sh" translate="no">
$ npm install express
~~~
</code></pre>
<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.

View File

@@ -1,8 +1,10 @@
---
### TRANSLATE ONLY "title" CONTENT IN THIS SECTION
layout: page
title: Serving static files in Express
menu: starter
lang: en
### END HEADER BLOCK - BEGIN GENERAL TRANSLATION
---
# Serving static files in Express
@@ -11,19 +13,19 @@ To serve static files such as images, CSS files, and JavaScript files, use the `
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
<pre><code class="language-javascript" translate="no">
app.use(express.static('public'));
~~~
</code></pre>
Now, you can load the files that are in the `public` directory:
~~~js
<pre><code class="language-javascript" translate="no">
http://localhost:3000/images/kitten.jpg
http://localhost:3000/css/style.css
http://localhost:3000/js/app.js
http://localhost:3000/images/bg.png
http://localhost:3000/hello.html
~~~
</code></pre>
<div class="doc-box doc-info">
The files are looked up relative to the static directory, so the name of the static directory is not part of the URL.
@@ -31,31 +33,31 @@ The files are looked up relative to the static directory, so the name of the sta
If you want to use multiple directories as static assets directories, you can call the `express.static` middleware function multiple times:
~~~js
<pre><code class="language-javascript" translate="no">
app.use(express.static('public'));
app.use(express.static('files'));
~~~
</code></pre>
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 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
<pre><code class="language-javascript" translate="no">
app.use('/static', express.static('public'));
~~~
</code></pre>
Now, you can load the files that are in the `public` directory from the `/static` path prefix.
~~~js
<pre><code class="language-javascript" translate="no">
http://localhost:3000/static/images/kitten.jpg
http://localhost:3000/static/css/style.css
http://localhost:3000/static/js/app.js
http://localhost:3000/static/images/bg.png
http://localhost:3000/static/hello.html
~~~
</code></pre>
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
<pre><code class="language-javascript" translate="no">
app.use('/static', express.static(__dirname + '/public'));
~~~
</code></pre>