diff --git a/README.md b/README.md
index 74b7a84be2..ed24bca043 100644
--- a/README.md
+++ b/README.md
@@ -39,9 +39,9 @@ Jekyll uses the [Liquid template engine](http://liquidmarkup.org/) for templatin
You can use [http://kramdown.gettalong.org/parser/gfm.html](GFM) fenced code blocks for JavaScript; for example:
```js
-var express = require('express');
-var app = express();
-app.listen(3000);
+var express = require('express')
+var app = express()
+app.listen(3000)
```
The default GitHub Pages syntax highlighting has been disabled in `_config.yml to allow highlighting with prism.js.
diff --git a/en/advanced/best-practice-performance.md b/en/advanced/best-practice-performance.md
index 8262c479df..a57b77e20f 100644
--- a/en/advanced/best-practice-performance.md
+++ b/en/advanced/best-practice-performance.md
@@ -31,10 +31,10 @@ 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
-var compression = require('compression');
-var express = require('express');
-var app = express();
-app.use(compression());
+var compression = require('compression')
+var express = require('express')
+var app = express()
+app.use(compression())
```
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.
@@ -96,15 +96,15 @@ This middleware function accepts a query field parameter named "params" that is
app.get('/search', function (req, res) {
// Simulating async operation
setImmediate(function () {
- var jsonStr = req.query.params;
+ var jsonStr = req.query.params
try {
- var jsonObj = JSON.parse(jsonStr);
- res.send('Success');
+ var jsonObj = JSON.parse(jsonStr)
+ res.send('Success')
} catch (e) {
- res.status(400).send('Invalid JSON string');
+ res.status(400).send('Invalid JSON string')
}
- });
-});
+ })
+})
```
However, try-catch works only for synchronous code. Because the Node platform is primarily asynchronous (particularly in a production environment), try-catch won't catch a lot of exceptions.
@@ -124,12 +124,12 @@ app.get('/', function (req, res, next) {
.then(function (csv) {
// handle csv
})
- .catch(next);
-});
+ .catch(next)
+})
app.use(function (err, req, res, next) {
// handle error
-});
+})
```
Now all errors asynchronous and synchronous get propagated to the error middleware.
@@ -144,7 +144,7 @@ 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)
-}));
+}))
```
For more information about error-handling by using promises, see:
diff --git a/en/advanced/best-practice-security.md b/en/advanced/best-practice-security.md
index a990df7e5b..6abf98c9cf 100644
--- a/en/advanced/best-practice-security.md
+++ b/en/advanced/best-practice-security.md
@@ -58,10 +58,12 @@ $ npm install --save helmet
Then to use it in your code:
```js
-...
-var helmet = require('helmet');
-app.use(helmet());
-...
+// ...
+
+var helmet = require('helmet')
+app.use(helmet())
+
+// ...
```
### At a minimum, disable X-Powered-By header
@@ -71,7 +73,7 @@ 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
-app.disable('x-powered-by');
+app.disable('x-powered-by')
```
If you use `helmet.js`, it takes care of this for you.
@@ -96,13 +98,12 @@ Using the default session cookie name can open your app to attacks. The securit
To avoid this problem, use generic cookie names; for example using [express-session](https://www.npmjs.com/package/express-session) middleware:
```js
-var session = require('express-session');
+var session = require('express-session')
app.set('trust proxy', 1) // trust first proxy
-app.use( session({
- secret : 's3Cur3',
- name : 'sessionId',
- })
-);
+app.use(session({
+ secret: 's3Cur3',
+ name: 'sessionId'
+}))
```
### Set cookie security options
@@ -118,22 +119,22 @@ Set the following cookie options to enhance security:
Here is an example using [cookie-session](https://www.npmjs.com/package/cookie-session) middleware:
```js
-var session = require('cookie-session');
-var express = require('express');
-var app = express();
+var session = require('cookie-session')
+var express = require('express')
+var app = express()
-var expiryDate = new Date( Date.now() + 60 * 60 * 1000 ); // 1 hour
+var expiryDate = new Date(Date.now() + 60 * 60 * 1000) // 1 hour
app.use(session({
name: 'session',
keys: ['key1', 'key2'],
- cookie: { secure: true,
- httpOnly: true,
- domain: 'example.com',
- path: 'foo/bar',
- expires: expiryDate
- }
- })
-);
+ cookie: {
+ secure: true,
+ httpOnly: true,
+ domain: 'example.com',
+ path: 'foo/bar',
+ expires: expiryDate
+ }
+}))
```
## Ensure your dependencies are secure
diff --git a/en/advanced/developing-template-engines.md b/en/advanced/developing-template-engines.md
index 8f20283a80..9e72962224 100755
--- a/en/advanced/developing-template-engines.md
+++ b/en/advanced/developing-template-engines.md
@@ -13,23 +13,23 @@ 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
-var fs = require('fs'); // this engine requires the fs module
+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) {
- if (err) return callback(new Error(err));
+ if (err) return callback(err)
// this is an extremely simple template engine
- var rendered = content.toString().replace('#title#', '
The routing system
@@ -131,15 +131,15 @@ Here is an example of chained route handlers that are defined by using the `app.
```js
app.route('/book')
- .get(function(req, res) {
- res.send('Get a random book');
+ .get(function (req, res) {
+ res.send('Get a random book')
})
- .post(function(req, res) {
- res.send('Add a book');
+ .post(function (req, res) {
+ res.send('Add a book')
+ })
+ .put(function (req, res) {
+ res.send('Update the book')
})
- .put(function(req, res) {
- res.send('Update the book');
- });
```
express.Router class
@@ -156,32 +156,34 @@ For example, create a router file named `birds.js` in the app directory,
with the following content:
```js
-var express = require('express');
-var router = express.Router();
+var express = require('express')
+var router = express.Router()
// middleware specific to this router
-router.use(function timeLog(req, res, next) {
- console.log('Time: ', Date.now());
- next();
-});
+router.use(function timeLog (req, res, next) {
+ console.log('Time: ', Date.now())
+ next()
+})
// define the home page route
-router.get('/', function(req, res) {
- res.send('Birds home page');
-});
+router.get('/', function (req, res) {
+ res.send('Birds home page')
+})
// define the about route
-router.get('/about', function(req, res) {
- res.send('About birds');
-});
+router.get('/about', function (req, res) {
+ res.send('About birds')
+})
-module.exports = router;
+module.exports = router
```
Then, load the router module in the app:
```js
-var birds = require('./birds');
-...
-app.use('/birds', birds);
+var birds = require('./birds')
+
+// ...
+
+app.use('/birds', birds)
```
The app will now be able to handle requests to the `/birds` and
@@ -321,37 +323,37 @@ Version 3 app
Consider an Express v.3 application with the following `app.js` file:
```js
-var express = require('express');
-var routes = require('./routes');
-var user = require('./routes/user');
-var http = require('http');
-var path = require('path');
+var express = require('express')
+var routes = require('./routes')
+var user = require('./routes/user')
+var http = require('http')
+var path = require('path')
-var app = express();
+var app = express()
// all environments
-app.set('port', process.env.PORT || 3000);
-app.set('views', path.join(__dirname, 'views'));
-app.set('view engine', 'pug');
-app.use(express.favicon());
-app.use(express.logger('dev'));
-app.use(express.methodOverride());
-app.use(express.session({ secret: 'your secret here' }));
-app.use(express.bodyParser());
-app.use(app.router);
-app.use(express.static(path.join(__dirname, 'public')));
+app.set('port', process.env.PORT || 3000)
+app.set('views', path.join(__dirname, 'views'))
+app.set('view engine', 'pug')
+app.use(express.favicon())
+app.use(express.logger('dev'))
+app.use(express.methodOverride())
+app.use(express.session({ secret: 'your secret here' }))
+app.use(express.bodyParser())
+app.use(app.router)
+app.use(express.static(path.join(__dirname, 'public')))
// development only
-if ('development' == app.get('env')) {
- app.use(express.errorHandler());
+if (app.get('env') === 'development') {
+ app.use(express.errorHandler())
}
-app.get('/', routes.index);
-app.get('/users', user.list);
+app.get('/', routes.index)
+app.get('/users', user.list)
-http.createServer(app).listen(app.get('port'), function(){
- console.log('Express server listening on port ' + app.get('port'));
-});
+http.createServer(app).listen(app.get('port'), function () {
+ console.log('Express server listening on port ' + app.get('port'))
+})
```
package.json
@@ -359,7 +361,7 @@ http.createServer(app).listen(app.get('port'), function(){
The accompanying version 3 `package.json` file might look
something like this:
-```js
+```json
{
"name": "application-name",
"version": "0.0.1",
@@ -407,7 +409,7 @@ Make the following changes to `app.js`:
Running the above `npm` command will update `package.json` as follows:
-```js
+```json
{
"name": "application-name",
"version": "0.0.1",
@@ -435,58 +437,58 @@ Then, remove invalid code, load the required middleware, and make other
changes as necessary. The `app.js` file will look like this:
```js
-var http = require('http');
-var express = require('express');
-var routes = require('./routes');
-var user = require('./routes/user');
-var path = require('path');
-
-var favicon = require('serve-favicon');
-var logger = require('morgan');
-var methodOverride = require('method-override');
-var session = require('express-session');
-var bodyParser = require('body-parser');
-var multer = require('multer');
-var errorHandler = require('errorhandler');
-
-var app = express();
+var http = require('http')
+var express = require('express')
+var routes = require('./routes')
+var user = require('./routes/user')
+var path = require('path')
+
+var favicon = require('serve-favicon')
+var logger = require('morgan')
+var methodOverride = require('method-override')
+var session = require('express-session')
+var bodyParser = require('body-parser')
+var multer = require('multer')
+var errorHandler = require('errorhandler')
+
+var app = express()
// all environments
-app.set('port', process.env.PORT || 3000);
-app.set('views', path.join(__dirname, 'views'));
-app.set('view engine', 'pug');
-app.use(favicon(__dirname + '/public/favicon.ico'));
-app.use(logger('dev'));
-app.use(methodOverride());
+app.set('port', process.env.PORT || 3000)
+app.set('views', path.join(__dirname, 'views'))
+app.set('view engine', 'pug')
+app.use(favicon(path.join(__dirname, '/public/favicon.ico')))
+app.use(logger('dev'))
+app.use(methodOverride())
app.use(session({ resave: true,
saveUninitialized: true,
- secret: 'uwotm8' }));
-app.use(bodyParser.json());
-app.use(bodyParser.urlencoded({ extended: true }));
-app.use(multer());
-app.use(express.static(path.join(__dirname, 'public')));
+ secret: 'uwotm8' }))
+app.use(bodyParser.json())
+app.use(bodyParser.urlencoded({ extended: true }))
+app.use(multer())
+app.use(express.static(path.join(__dirname, 'public')))
-app.get('/', routes.index);
-app.get('/users', user.list);
+app.get('/', routes.index)
+app.get('/users', user.list)
// error handling middleware should be loaded after the loading the routes
-if ('development' == app.get('env')) {
- app.use(errorHandler());
+if (app.get('env') === 'development') {
+ app.use(errorHandler())
}
-var server = http.createServer(app);
-server.listen(app.get('port'), function(){
- console.log('Express server listening on port ' + app.get('port'));
-});
+var server = http.createServer(app)
+server.listen(app.get('port'), function () {
+ console.log('Express server listening on port ' + app.get('port'))
+})
```
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:
```js
-app.listen(app.get('port'), function(){
- console.log('Express server listening on port ' + app.get('port'));
-});
+app.listen(app.get('port'), function () {
+ console.log('Express server listening on port ' + app.get('port'))
+})
```
@@ -583,17 +585,17 @@ 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);
+app.set('port', process.env.PORT || 3000)
-var server = app.listen(app.get('port'), function() {
- debug('Express server listening on port ' + server.address().port);
-});
+var server = app.listen(app.get('port'), function () {
+ debug('Express server listening on port ' + server.address().port)
+})
```
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');
+var debug = require('debug')('app4')
```
Next, change `"start": "node ./bin/www"` in the `package.json` file to `"start": "node app.js"`.
diff --git a/en/guide/routing.md b/en/guide/routing.md
index 6bf6c63d52..32fd956e70 100755
--- a/en/guide/routing.md
+++ b/en/guide/routing.md
@@ -14,13 +14,13 @@ For an introduction to routing, see [Basic routing](/{{ page.lang }}/starter/bas
The following code is an example of a very basic route.
```js
-var express = require('express');
-var app = express();
+var express = require('express')
+var app = express()
// respond with "hello world" when a GET request is made to the homepage
-app.get('/', function(req, res) {
- res.send('hello world');
-});
+app.get('/', function (req, res) {
+ res.send('hello world')
+})
```
Route methods
@@ -32,13 +32,13 @@ The following code is an example of routes that are defined for the GET and the
```js
// GET method route
app.get('/', function (req, res) {
- res.send('GET request to the homepage');
-});
+ res.send('GET request to the homepage')
+})
// POST method route
app.post('/', function (req, res) {
- res.send('POST request to the homepage');
-});
+ res.send('POST request to the homepage')
+})
```
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`.
@@ -54,9 +54,9 @@ In the following example, the handler will be executed for requests to "/secret"
```js
app.all('/secret', function (req, res, next) {
- console.log('Accessing the secret section ...');
- next(); // pass control to the next handler
-});
+ console.log('Accessing the secret section ...')
+ next() // pass control to the next handler
+})
```
Route paths
@@ -79,24 +79,24 @@ This route path will match requests to the root route, `/`.
```js
app.get('/', function (req, res) {
- res.send('root');
-});
+ res.send('root')
+})
```
This route path will match requests to `/about`.
```js
app.get('/about', function (req, res) {
- res.send('about');
-});
+ res.send('about')
+})
```
This route path will match requests to `/random.text`.
```js
app.get('/random.text', function (req, res) {
- res.send('random.text');
-});
+ res.send('random.text')
+})
```
Here are some examples of route paths based on string patterns.
@@ -104,33 +104,33 @@ Here are some examples of route paths based on string patterns.
This route path will match `acd` and `abcd`.
```js
-app.get('/ab?cd', function(req, res) {
- res.send('ab?cd');
-});
+app.get('/ab?cd', function (req, res) {
+ res.send('ab?cd')
+})
```
This route path will match `abcd`, `abbcd`, `abbbcd`, and so on.
```js
-app.get('/ab+cd', function(req, res) {
- res.send('ab+cd');
-});
+app.get('/ab+cd', function (req, res) {
+ res.send('ab+cd')
+})
```
This route path will match `abcd`, `abxcd`, `abRANDOMcd`, `ab123cd`, and so on.
```js
-app.get('/ab*cd', function(req, res) {
- res.send('ab*cd');
-});
+app.get('/ab*cd', function (req, res) {
+ res.send('ab*cd')
+})
```
This route path will match `/abe` and `/abcde`.
```js
-app.get('/ab(cd)?e', function(req, res) {
- res.send('ab(cd)?e');
-});
+app.get('/ab(cd)?e', function (req, res) {
+ res.send('ab(cd)?e')
+})
```
Examples of route paths based on regular expressions:
@@ -138,17 +138,17 @@ Examples of route paths based on regular expressions:
This route path will match anything with an "a" in the route name.
```js
-app.get(/a/, function(req, res) {
- res.send('/a/');
-});
+app.get(/a/, function (req, res) {
+ res.send('/a/')
+})
```
This route path will match `butterfly` and `dragonfly`, but not `butterflyman`, `dragonflyman`, and so on.
```js
-app.get(/.*fly$/, function(req, res) {
- res.send('/.*fly$/');
-});
+app.get(/.*fly$/, function (req, res) {
+ res.send('/.*fly$/')
+})
```
Route parameters
@@ -164,9 +164,9 @@ req.params: { "userId": "34", "bookId": "8989" }
To define routes with route parameters, simply specify the route parameters in the path of the route as shown below.
```js
-app.get('/users/:userId/books/:bookId', function(req, res) {
- res.send(req.params);
-});
+app.get('/users/:userId/books/:bookId', function (req, res) {
+ res.send(req.params)
+})
```
Since the hyphen (`-`) and the dot (`.`) are interpreted literally, they can be used along with route parameters for useful purposes.
@@ -197,60 +197,60 @@ A single callback function can handle a route. For example:
```js
app.get('/example/a', function (req, res) {
- res.send('Hello from A!');
-});
+ res.send('Hello from A!')
+})
```
More than one callback function can handle a route (make sure you specify the `next` object). For example:
```js
app.get('/example/b', function (req, res, next) {
- console.log('the response will be sent by the next function ...');
- next();
+ console.log('the response will be sent by the next function ...')
+ next()
}, function (req, res) {
- res.send('Hello from B!');
-});
+ res.send('Hello from B!')
+})
```
An array of callback functions can handle a route. For example:
```js
var cb0 = function (req, res, next) {
- console.log('CB0');
- next();
+ console.log('CB0')
+ next()
}
var cb1 = function (req, res, next) {
- console.log('CB1');
- next();
+ console.log('CB1')
+ next()
}
var cb2 = function (req, res) {
- res.send('Hello from C!');
+ res.send('Hello from C!')
}
-app.get('/example/c', [cb0, cb1, cb2]);
+app.get('/example/c', [cb0, cb1, cb2])
```
A combination of independent functions and arrays of functions can handle a route. For example:
```js
var cb0 = function (req, res, next) {
- console.log('CB0');
- next();
+ console.log('CB0')
+ next()
}
var cb1 = function (req, res, next) {
- console.log('CB1');
- next();
+ console.log('CB1')
+ next()
}
app.get('/example/d', [cb0, cb1], function (req, res, next) {
- console.log('the response will be sent by the next function ...');
- next();
+ console.log('the response will be sent by the next function ...')
+ next()
}, function (req, res) {
- res.send('Hello from D!');
-});
+ res.send('Hello from D!')
+})
```
Response methods
@@ -278,15 +278,15 @@ Here is an example of chained route handlers that are defined by using `app.rout
```js
app.route('/book')
- .get(function(req, res) {
- res.send('Get a random book');
+ .get(function (req, res) {
+ res.send('Get a random book')
+ })
+ .post(function (req, res) {
+ res.send('Add a book')
})
- .post(function(req, res) {
- res.send('Add a book');
+ .put(function (req, res) {
+ res.send('Update the book')
})
- .put(function(req, res) {
- res.send('Update the book');
- });
```
express.Router
@@ -298,32 +298,34 @@ 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
-var express = require('express');
-var router = express.Router();
+var express = require('express')
+var router = express.Router()
// middleware that is specific to this router
-router.use(function timeLog(req, res, next) {
- console.log('Time: ', Date.now());
- next();
-});
+router.use(function timeLog (req, res, next) {
+ console.log('Time: ', Date.now())
+ next()
+})
// define the home page route
-router.get('/', function(req, res) {
- res.send('Birds home page');
-});
+router.get('/', function (req, res) {
+ res.send('Birds home page')
+})
// define the about route
-router.get('/about', function(req, res) {
- res.send('About birds');
-});
+router.get('/about', function (req, res) {
+ res.send('About birds')
+})
-module.exports = router;
+module.exports = router
```
Then, load the router module in the app:
```js
-var birds = require('./birds');
-...
-app.use('/birds', birds);
+var birds = require('./birds')
+
+// ...
+
+app.use('/birds', birds)
```
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.
diff --git a/en/guide/using-middleware.md b/en/guide/using-middleware.md
index 30662c2ac2..3fb27bc9f0 100644
--- a/en/guide/using-middleware.md
+++ b/en/guide/using-middleware.md
@@ -39,12 +39,12 @@ Bind application-level middleware to an instance of the [app object](/{{ page.la
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();
+var app = express()
app.use(function (req, res, next) {
- console.log('Time:', Date.now());
- next();
-});
+ console.log('Time:', Date.now())
+ next()
+})
```
This example shows a middleware function mounted on the `/user/:id` path. The function is executed for any type of
@@ -52,30 +52,30 @@ HTTP request on the `/user/:id` path.
```js
app.use('/user/:id', function (req, res, next) {
- console.log('Request Type:', req.method);
- next();
-});
+ console.log('Request Type:', req.method)
+ next()
+})
```
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');
-});
+ res.send('USER')
+})
```
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
-app.use('/user/:id', function(req, res, next) {
- console.log('Request URL:', req.originalUrl);
- next();
+app.use('/user/:id', function (req, res, next) {
+ console.log('Request URL:', req.originalUrl)
+ next()
}, function (req, res, next) {
- console.log('Request Type:', req.method);
- next();
-});
+ console.log('Request Type:', req.method)
+ next()
+})
```
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.
@@ -84,16 +84,16 @@ This example shows a middleware sub-stack that handles GET requests to the `/use
```js
app.get('/user/:id', function (req, res, next) {
- console.log('ID:', req.params.id);
- next();
+ console.log('ID:', req.params.id)
+ next()
}, function (req, res, next) {
- res.send('User Info');
-});
+ res.send('User Info')
+})
// handler for the /user/:id path, which prints the user ID
app.get('/user/:id', function (req, res, next) {
- res.end(req.params.id);
-});
+ res.end(req.params.id)
+})
```
To skip the rest of the middleware functions from a router middleware stack, call `next('route')` to pass control to the next route.
@@ -104,18 +104,18 @@ This example shows a middleware sub-stack that handles GET requests to the `/use
```js
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');
+ if (req.params.id === 0) next('route')
// otherwise pass the control to the next middleware function in this stack
- else next(); //
+ else next()
}, function (req, res, next) {
// render a regular page
- res.render('regular');
-});
+ res.render('regular')
+})
// handler for the /user/:id path, which renders a special page
app.get('/user/:id', function (req, res, next) {
- res.render('special');
-});
+ res.render('special')
+})
```
Router-level middleware
@@ -123,50 +123,50 @@ app.get('/user/:id', function (req, res, next) {
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();
+var router = express.Router()
```
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
-var app = express();
-var router = express.Router();
+var app = express()
+var router = express.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();
-});
+ console.log('Time:', Date.now())
+ next()
+})
// 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();
+router.use('/user/:id', function (req, res, next) {
+ console.log('Request URL:', req.originalUrl)
+ next()
}, function (req, res, next) {
- console.log('Request Type:', req.method);
- next();
-});
+ console.log('Request Type:', req.method)
+ next()
+})
// a middleware sub-stack that handles GET requests to the /user/:id path
router.get('/user/:id', function (req, res, next) {
// if the user ID is 0, skip to the next router
- if (req.params.id == 0) next('route');
+ if (req.params.id === 0) next('route')
// otherwise pass control to the next middleware function in this stack
- else next(); //
+ else next()
}, function (req, res, next) {
// render a regular page
- res.render('regular');
-});
+ res.render('regular')
+})
// 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');
-});
+ console.log(req.params.id)
+ res.render('special')
+})
// mount the router on the app
-app.use('/', router);
+app.use('/', router)
```
Error-handling middleware
@@ -178,10 +178,10 @@ 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
-app.use(function(err, req, res, next) {
- console.error(err.stack);
- res.status(500).send('Something broke!');
-});
+app.use(function (err, req, res, next) {
+ console.error(err.stack)
+ res.status(500).send('Something broke!')
+})
```
For details about error-handling middleware, see: [Error handling](/{{ page.lang }}/guide/error-handling.html).
@@ -214,19 +214,19 @@ var options = {
maxAge: '1d',
redirect: false,
setHeaders: function (res, path, stat) {
- res.set('x-timestamp', Date.now());
+ res.set('x-timestamp', Date.now())
}
}
-app.use(express.static('public', options));
+app.use(express.static('public', options))
```
You can have more than one static directory per app:
```js
-app.use(express.static('public'));
-app.use(express.static('uploads'));
-app.use(express.static('files'));
+app.use(express.static('public'))
+app.use(express.static('uploads'))
+app.use(express.static('files'))
```
For more details about the `serve-static` function and its options, see: [serve-static](https://github.com/expressjs/serve-static) documentation.
@@ -244,12 +244,12 @@ $ npm install cookie-parser
```
```js
-var express = require('express');
-var app = express();
-var cookieParser = require('cookie-parser');
+var express = require('express')
+var app = express()
+var cookieParser = require('cookie-parser')
// load the cookie-parsing middleware
-app.use(cookieParser());
+app.use(cookieParser())
```
For a partial list of third-party middleware functions that are commonly used with Express, see: [Third-party middleware](../resources/middleware.html).
diff --git a/en/guide/using-template-engines.md b/en/guide/using-template-engines.md
index fde42bcc58..23905e50e5 100755
--- a/en/guide/using-template-engines.md
+++ b/en/guide/using-template-engines.md
@@ -44,12 +44,12 @@ After the view engine is set, you don't have to specify the engine or load the t
Express loads the module internally, as shown below (for the above example).
```js
-app.set('view engine', 'pug');
+app.set('view engine', 'pug')
```
Create a Pug template file named `index.pug` in the `views` directory, with the following content:
-```js
+```pug
html
head
title= title
@@ -62,8 +62,8 @@ you must specify the extension of the `view` file. Otherwise, you can omit it.
```js
app.get('/', function (req, res) {
- res.render('index', { title: 'Hey', message: 'Hello there!'});
-});
+ res.render('index', { title: 'Hey', message: 'Hello there!' })
+})
```
When you make a request to the home page, the `index.pug` file will be rendered as HTML.
diff --git a/en/guide/writing-middleware.md b/en/guide/writing-middleware.md
index 39cd003302..080c5ee5d9 100755
--- a/en/guide/writing-middleware.md
+++ b/en/guide/writing-middleware.md
@@ -50,14 +50,14 @@ one called `myLogger` that prints a simple log message and another called `reque
displays the timestamp of the HTTP request.
```js
-var express = require('express');
-var app = express();
+var express = require('express')
+var app = express()
app.get('/', function (req, res) {
- res.send('Hello World!');
-});
+ res.send('Hello World!')
+})
-app.listen(3000);
+app.listen(3000)
```
Middleware function myLogger
@@ -65,9 +65,9 @@ Here is a simple example of a middleware function called "myLogger". This functi
```js
var myLogger = function (req, res, next) {
- console.log('LOGGED');
- next();
-};
+ console.log('LOGGED')
+ next()
+}
```
@@ -80,21 +80,21 @@ To load the middleware function, call `app.use()`, specifying the middleware fun
For example, the following code loads the `myLogger` middleware function before the route to the root path (/).
```js
-var express = require('express');
-var app = express();
+var express = require('express')
+var app = express()
var myLogger = function (req, res, next) {
- console.log('LOGGED');
- next();
-};
+ console.log('LOGGED')
+ next()
+}
-app.use(myLogger);
+app.use(myLogger)
app.get('/', function (req, res) {
- res.send('Hello World!');
-});
+ res.send('Hello World!')
+})
-app.listen(3000);
+app.listen(3000)
```
Every time the app receives a request, it prints the message "LOGGED" to the terminal.
@@ -112,31 +112,31 @@ to the request object.
```js
var requestTime = function (req, res, next) {
- req.requestTime = Date.now();
- next();
-};
+ req.requestTime = Date.now()
+ next()
+}
```
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');
-var app = express();
+var express = require('express')
+var app = express()
var requestTime = function (req, res, next) {
- req.requestTime = Date.now();
- next();
-};
+ req.requestTime = Date.now()
+ next()
+}
-app.use(requestTime);
+app.use(requestTime)
app.get('/', function (req, res) {
- var responseText = 'Hello World!
';
- responseText += 'Requested at: ' + req.requestTime + '';
- res.send(responseText);
-});
+ var responseText = 'Hello World!
'
+ responseText += 'Requested at: ' + req.requestTime + ''
+ res.send(responseText)
+})
-app.listen(3000);
+app.listen(3000)
```
When you make a request to the root of the app, the app now displays the timestamp of your request in the browser.
diff --git a/en/resources/middleware/compression.md b/en/resources/middleware/compression.md
index 46d9294158..72a9c1d743 100644
--- a/en/resources/middleware/compression.md
+++ b/en/resources/middleware/compression.md
@@ -153,7 +153,7 @@ function that is an extension of the default function.
```js
app.use(compression({filter: shouldCompress}))
-function shouldCompress(req, res) {
+function shouldCompress (req, res) {
if (req.headers['x-no-compression']) {
// don't compress responses with this request header
return false
@@ -200,7 +200,7 @@ actually make it to the client.
```js
var compression = require('compression')
-var express = require('express')
+var express = require('express')
var app = express()
diff --git a/en/resources/middleware/connect-rid.md b/en/resources/middleware/connect-rid.md
index 4fb5a61a87..3c20981f93 100644
--- a/en/resources/middleware/connect-rid.md
+++ b/en/resources/middleware/connect-rid.md
@@ -27,11 +27,11 @@ $ npm install connect-rid
## Usage
```js
-var rid = require('connect-rid');
+var rid = require('connect-rid')
app.use(rid({
// headerName: 'X-RID'
-}));
+}))
```
## License
diff --git a/en/resources/middleware/cookie-parser.md b/en/resources/middleware/cookie-parser.md
index 96574e936c..2265addc23 100644
--- a/en/resources/middleware/cookie-parser.md
+++ b/en/resources/middleware/cookie-parser.md
@@ -28,7 +28,7 @@ $ npm install cookie-parser
## API
```js
-var express = require('express')
+var express = require('express')
var cookieParser = require('cookie-parser')
var app = express()
@@ -64,13 +64,13 @@ The `secret` argument can be an array or string. If a string is provided, this i
## Example
```js
-var express = require('express')
+var express = require('express')
var cookieParser = require('cookie-parser')
var app = express()
app.use(cookieParser())
-app.get('/', function(req, res) {
+app.get('/', function (req, res) {
console.log('Cookies: ', req.cookies)
})
diff --git a/en/resources/middleware/cors.md b/en/resources/middleware/cors.md
index 2bde646250..f21ec41e61 100644
--- a/en/resources/middleware/cors.md
+++ b/en/resources/middleware/cors.md
@@ -40,78 +40,78 @@ $ npm install cors
```javascript
var express = require('express')
- , cors = require('cors')
- , app = express();
+var cors = require('cors')
+var app = express()
-app.use(cors());
+app.use(cors())
-app.get('/products/:id', function(req, res, next){
- res.json({msg: 'This is CORS-enabled for all origins!'});
-});
+app.get('/products/:id', function (req, res, next) {
+ res.json({msg: 'This is CORS-enabled for all origins!'})
+})
-app.listen(80, function(){
- console.log('CORS-enabled web server listening on port 80');
-});
+app.listen(80, function () {
+ console.log('CORS-enabled web server listening on port 80')
+})
```
### Enable CORS for a Single Route
```javascript
var express = require('express')
- , cors = require('cors')
- , app = express();
+var cors = require('cors')
+var app = express()
-app.get('/products/:id', cors(), function(req, res, next){
- res.json({msg: 'This is CORS-enabled for all origins!'});
-});
+app.get('/products/:id', cors(), function (req, res, next) {
+ res.json({msg: 'This is CORS-enabled for all origins!'})
+})
-app.listen(80, function(){
- console.log('CORS-enabled web server listening on port 80');
-});
+app.listen(80, function () {
+ console.log('CORS-enabled web server listening on port 80')
+})
```
### Configuring CORS
```javascript
var express = require('express')
- , cors = require('cors')
- , app = express();
+var cors = require('cors')
+var app = express()
var corsOptions = {
origin: 'http://example.com'
-};
+}
-app.get('/products/:id', cors(corsOptions), function(req, res, next){
- res.json({msg: 'This is CORS-enabled for only example.com.'});
-});
+app.get('/products/:id', cors(corsOptions), function (req, res, next) {
+ res.json({msg: 'This is CORS-enabled for only example.com.'})
+})
-app.listen(80, function(){
- console.log('CORS-enabled web server listening on port 80');
-});
+app.listen(80, function () {
+ console.log('CORS-enabled web server listening on port 80')
+})
```
### Configuring CORS w/ Dynamic Origin
```javascript
var express = require('express')
- , cors = require('cors')
- , app = express();
+var cors = require('cors')
+var app = express()
-var whitelist = ['http://example1.com', 'http://example2.com'];
+var whitelist = ['http://example1.com', 'http://example2.com']
var corsOptions = {
- origin: function(origin, callback){
- var originIsWhitelisted = whitelist.indexOf(origin) !== -1;
- callback(null, originIsWhitelisted);
+ origin: function (origin, callback) {
+ var originIsWhitelisted = whitelist.indexOf(origin) !== -1
+ callback(null, originIsWhitelisted)
}
-};
+}
-app.get('/products/:id', cors(corsOptions), function(req, res, next){
- res.json({msg: 'This is CORS-enabled for a whitelisted domain.'});
-});
+app.get('/products/:id', cors(corsOptions), function (req, res, next) {
+ res.json({msg: 'This is CORS-enabled for a whitelisted domain.'})
+})
-app.listen(80, function(){
- console.log('CORS-enabled web server listening on port 80');
-});
+app.listen(80, function () {
+ console.log('CORS-enabled web server listening on port 80')
+})
```
### Enabling CORS Pre-Flight
@@ -125,50 +125,50 @@ to support:
```javascript
var express = require('express')
- , cors = require('cors')
- , app = express();
+var cors = require('cors')
+var app = express()
-app.options('/products/:id', cors()); // enable pre-flight request for DELETE request
-app.del('/products/:id', cors(), function(req, res, next){
- res.json({msg: 'This is CORS-enabled for all origins!'});
-});
+app.options('/products/:id', cors()) // enable pre-flight request for DELETE request
+app.del('/products/:id', cors(), function (req, res, next) {
+ res.json({msg: 'This is CORS-enabled for all origins!'})
+})
-app.listen(80, function(){
- console.log('CORS-enabled web server listening on port 80');
-});
+app.listen(80, function () {
+ console.log('CORS-enabled web server listening on port 80')
+})
```
You can also enable pre-flight across-the-board like so:
-```
-app.options('*', cors()); // include before other routes
+```javascript
+app.options('*', cors()) // include before other routes
```
### Configuring CORS Asynchronously
```javascript
var express = require('express')
- , cors = require('cors')
- , app = express();
-
-var whitelist = ['http://example1.com', 'http://example2.com'];
-var corsOptionsDelegate = function(req, callback){
- var corsOptions;
- if(whitelist.indexOf(req.header('Origin')) !== -1){
- corsOptions = { origin: true }; // reflect (enable) the requested origin in the CORS response
- }else{
- corsOptions = { origin: false }; // disable CORS for this request
+var cors = require('cors')
+var app = express()
+
+var whitelist = ['http://example1.com', 'http://example2.com']
+var corsOptionsDelegate = function (req, callback) {
+ var corsOptions
+ if (whitelist.indexOf(req.header('Origin')) !== -1) {
+ corsOptions = { origin: true } // reflect (enable) the requested origin in the CORS response
+ } else {
+ corsOptions = { origin: false } // disable CORS for this request
}
- callback(null, corsOptions); // callback expects two parameters: error and options
-};
+ callback(null, corsOptions) // callback expects two parameters: error and options
+}
-app.get('/products/:id', cors(corsOptionsDelegate), function(req, res, next){
- res.json({msg: 'This is CORS-enabled for a whitelisted domain.'});
-});
+app.get('/products/:id', cors(corsOptionsDelegate), function (req, res, next) {
+ res.json({msg: 'This is CORS-enabled for a whitelisted domain.'})
+})
-app.listen(80, function(){
- console.log('CORS-enabled web server listening on port 80');
-});
+app.listen(80, function () {
+ console.log('CORS-enabled web server listening on port 80')
+})
```
## Configuration Options
diff --git a/en/resources/middleware/csurf.md b/en/resources/middleware/csurf.md
index fad10e7aa5..3d75aecdfd 100644
--- a/en/resources/middleware/csurf.md
+++ b/en/resources/middleware/csurf.md
@@ -130,12 +130,12 @@ var app = express()
// we need this because "cookie" is true in csrfProtection
app.use(cookieParser())
-app.get('/form', csrfProtection, function(req, res) {
+app.get('/form', csrfProtection, function (req, res) {
// pass the csrfToken to the view
res.render('send', { csrfToken: req.csrfToken() })
})
-app.post('/process', parseForm, csrfProtection, function(req, res) {
+app.post('/process', parseForm, csrfProtection, function (req, res) {
res.send('data is being processed')
})
```
diff --git a/en/resources/middleware/errorhandler.md b/en/resources/middleware/errorhandler.md
index faa4d95ea2..8d99645639 100644
--- a/en/resources/middleware/errorhandler.md
+++ b/en/resources/middleware/errorhandler.md
@@ -107,7 +107,7 @@ if (process.env.NODE_ENV === 'development') {
app.use(errorhandler({log: errorNotification}))
}
-function errorNotification(err, str, req) {
+function errorNotification (err, str, req) {
var title = 'Error in ' + req.method + ' ' + req.url
notifier.notify({
diff --git a/en/resources/middleware/method-override.md b/en/resources/middleware/method-override.md
index f4e2a605f8..1e09155e53 100644
--- a/en/resources/middleware/method-override.md
+++ b/en/resources/middleware/method-override.md
@@ -73,7 +73,7 @@ typically be used in conjunction with `XMLHttpRequest` on implementations
that do not support the method you are trying to use.
```js
-var connect = require('connect')
+var connect = require('connect')
var methodOverride = require('method-override')
// override with the X-HTTP-Method-Override header in the request
@@ -89,7 +89,7 @@ xhr.open('post', '/resource', true)
xhr.setRequestHeader('X-HTTP-Method-Override', 'DELETE')
xhr.send()
-function onload() {
+function onload () {
alert('got response: ' + this.responseText)
}
```
@@ -105,7 +105,7 @@ query value would typically be used in conjunction with plain HTML
newer methods.
```js
-var connect = require('connect')
+var connect = require('connect')
var methodOverride = require('method-override')
// override with POST having ?_method=DELETE
@@ -123,7 +123,7 @@ Example call with query override using HTML `
diff --git a/package.json b/package.json
new file mode 100644
index 0000000000..b82b3fdb50
--- /dev/null
+++ b/package.json
@@ -0,0 +1,24 @@
+{
+ "name": "expressjs.com",
+ "version": "0.0.0",
+ "private": true,
+ "scripts": {
+ "test": "eslint --ext md en/"
+ },
+ "devDependencies": {
+ "eslint": "^3.7.1",
+ "eslint-config-standard": "^6.2.0",
+ "eslint-plugin-markdown": "^1.0.0-beta.2",
+ "eslint-plugin-promise": "^2.0.1",
+ "eslint-plugin-standard": "^2.0.1"
+ },
+ "eslintConfig": {
+ "extends": "standard",
+ "plugins": ["markdown"],
+ "rules": {
+ "handle-callback-err": 0,
+ "no-undef": 0,
+ "no-unused-vars": 0
+ }
+ }
+}