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#', ''+ options.title +'') - .replace('#message#', '

'+ options.message +'

'); - return callback(null, rendered); - }); -}); -app.set('views', './views'); // specify the views directory -app.set('view engine', 'ntl'); // register the template engine + var rendered = content.toString().replace('#title#', '' + options.title + '') + .replace('#message#', '

' + options.message + '

') + return callback(null, rendered) + }) +}) +app.set('views', './views') // specify the views directory +app.set('view engine', 'ntl') // register the template engine ``` Your app will now be able to render `.ntl` files. Create a file named `index.ntl` in the `views` directory with the following content. -```js +```text #title# #message# ``` @@ -37,8 +37,8 @@ Then, create the following route in your app. ```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, `index.ntl` will be rendered as HTML. diff --git a/en/guide/behind-proxies.md b/en/guide/behind-proxies.md index 6f2b1605ec..1796d6a3cc 100755 --- a/en/guide/behind-proxies.md +++ b/en/guide/behind-proxies.md @@ -59,9 +59,9 @@ Custom trust implementation. Use this only if you know what you are doing. ```js app.set('trust proxy', function (ip) { - if (ip === '127.0.0.1' || ip === '123.123.123.123') return true; // trusted IPs - else return false; -}); + if (ip === '127.0.0.1' || ip === '123.123.123.123') return true // trusted IPs + else return false +}) ``` diff --git a/en/guide/database-integration.md b/en/guide/database-integration.md index 2ac81b43a3..4eaef7264f 100644 --- a/en/guide/database-integration.md +++ b/en/guide/database-integration.md @@ -41,13 +41,13 @@ $ npm install cassandra-driver **Example** ```js -var cassandra = require('cassandra-driver'); -var client = new cassandra.Client({ contactPoints: ['localhost']}); +var cassandra = require('cassandra-driver') +var client = new cassandra.Client({ contactPoints: ['localhost'] }) -client.execute('select key from system.local', function(err, result) { - if (err) throw err; - console.log(result.rows[0]); -}); +client.execute('select key from system.local', function (err, result) { + if (err) throw err + console.log(result.rows[0]) +}) ``` @@ -64,26 +64,28 @@ $ npm install couchbase **Example** ```js -var couchbase = require("couchbase"); -var bucket = (new couchbase.Cluster("http://localhost:8091")).openBucket("bucketName"); +var couchbase = require('couchbase') +var bucket = (new couchbase.Cluster('http://localhost:8091')).openBucket('bucketName') // add a document to a bucket -bucket.insert("document-key", { name: "Matt", shoeSize: 13}, function(error, result) { - if(error) - console.log(error); - else - console.log(result); -}); +bucket.insert('document-key', { name: 'Matt', shoeSize: 13 }, function (err, result) { + if (err) { + console.log(err) + } else { + console.log(result) + } +}) // get all documents with shoe size 13 -var n1ql = "SELECT d.* FROM `bucketName` d WHERE shoeSize = $1;" -var query = N1qlQuery.fromString(n1ql); -bucket.query(query, [13], function(error, result) { - if(error) - console.log(error); - else - console.log(result); -}); +var n1ql = 'SELECT d.* FROM `bucketName` d WHERE shoeSize = $1' +var query = N1qlQuery.fromString(n1ql) +bucket.query(query, [13], function (err, result) { + if (err) { + console.log(err) + } else { + console.log(result) + } +}) ``` @@ -100,21 +102,27 @@ $ npm install nano **Example** ```js -var nano = require('nano')('http://localhost:5984'); -nano.db.create('books'); -var books = nano.db.use('books'); - -//Insert a book document in the books database -books.insert({name: 'The Art of war'}, null, function(err, body) { - if (!err){ - console.log(body); +var nano = require('nano')('http://localhost:5984') +nano.db.create('books') +var books = nano.db.use('books') + +// Insert a book document in the books database +books.insert({ name: 'The Art of war' }, null, function (err, body) { + if (err) { + console.log(err) + } else { + console.log(body) } -}); +}) -//Get a list of all books -books.list(function(err, body){ - console.log(body.rows); -}); +// Get a list of all books +books.list(function (err, body) { + if (err) { + console.log(err) + } else { + console.log(body.rows) + } +}) ``` @@ -131,18 +139,18 @@ $ npm install level levelup leveldown **Example** ```js -var levelup = require('levelup'); -var db = levelup('./mydb'); +var levelup = require('levelup') +var db = levelup('./mydb') db.put('name', 'LevelUP', function (err) { + if (err) return console.log('Ooops!', err) - if (err) return console.log('Ooops!', err); db.get('name', function (err, value) { - if (err) return console.log('Ooops!', err); - console.log('name=' + value); - }); + if (err) return console.log('Ooops!', err) -}); + console.log('name=' + value) + }) +}) ``` @@ -159,21 +167,22 @@ $ npm install mysql **Example** ```js -var mysql = require('mysql'); +var mysql = require('mysql') var connection = mysql.createConnection({ - host : 'localhost', - user : 'dbuser', - password : 's3kreee7' -}); + host: 'localhost', + user: 'dbuser', + password: 's3kreee7' +}) -connection.connect(); +connection.connect() -connection.query('SELECT 1 + 1 AS solution', function(err, rows, fields) { - if (err) throw err; - console.log('The solution is: ', rows[0].solution); -}); +connection.query('SELECT 1 + 1 AS solution', function (err, rows, fields) { + if (err) throw err -connection.end(); + console.log('The solution is: ', rows[0].solution) +}) + +connection.end() ``` @@ -190,19 +199,17 @@ $ npm install mongodb **Example** ```js -var MongoClient = require('mongodb').MongoClient; +var MongoClient = require('mongodb').MongoClient -MongoClient.connect('mongodb://localhost:27017/animals', function(err, db) { - if (err) { - throw err; - } - db.collection('mammals').find().toArray(function(err, result) { - if (err) { - throw err; - } - console.log(result); - }); -}); +MongoClient.connect('mongodb://localhost:27017/animals', function (err, db) { + if (err) throw err + + db.collection('mammals').find().toArray(function (err, result) { + if (err) throw err + + console.log(result) + }) +}) ``` If you want an object model driver for MongoDB, look at [Mongoose](https://github.com/LearnBoost/mongoose). @@ -221,16 +228,16 @@ $ npm install apoc **Example** ```js -var apoc = require('apoc'); +var apoc = require('apoc') apoc.query('match (n) return n').exec().then( function (response) { - console.log(response); + console.log(response) }, function (fail) { - console.log(fail); + console.log(fail) } -); +) ``` @@ -247,16 +254,16 @@ $ npm install pg-promise **Example** ```js -var pgp = require("pg-promise")(/*options*/); -var db = pgp("postgres://username:password@host:port/database"); - -db.one("SELECT $1 AS value", 123) - .then(function (data) { - console.log("DATA:", data.value); - }) - .catch(function (error) { - console.log("ERROR:", error); - }); +var pgp = require('pg-promise')(/*options*/) +var db = pgp('postgres://username:password@host:port/database') + +db.one('SELECT $1 AS value', 123) + .then(function (data) { + console.log('DATA:', data.value) + }) + .catch(function (error) { + console.log('ERROR:', error) + }) ``` @@ -273,26 +280,25 @@ $ npm install redis **Example** ```js -var client = require('redis').createClient(); +var client = require('redis').createClient() client.on('error', function (err) { - console.log('Error ' + err); -}); + console.log('Error ' + err) +}) -client.set('string key', 'string val', redis.print); -client.hset('hash key', 'hashtest 1', 'some value', redis.print); -client.hset(['hash key', 'hashtest 2', 'some other value'], redis.print); +client.set('string key', 'string val', redis.print) +client.hset('hash key', 'hashtest 1', 'some value', redis.print) +client.hset(['hash key', 'hashtest 2', 'some other value'], redis.print) client.hkeys('hash key', function (err, replies) { + console.log(replies.length + ' replies:') - console.log(replies.length + ' replies:'); replies.forEach(function (reply, i) { - console.log(' ' + i + ': ' + reply); - }); + console.log(' ' + i + ': ' + reply) + }) - client.quit(); - -}); + client.quit() +}) ``` @@ -309,26 +315,25 @@ $ npm install sqlite3 **Example** ```js -var sqlite3 = require('sqlite3').verbose(); -var db = new sqlite3.Database(':memory:'); - -db.serialize(function() { +var sqlite3 = require('sqlite3').verbose() +var db = new sqlite3.Database(':memory:') - db.run('CREATE TABLE lorem (info TEXT)'); - var stmt = db.prepare('INSERT INTO lorem VALUES (?)'); +db.serialize(function () { + db.run('CREATE TABLE lorem (info TEXT)') + var stmt = db.prepare('INSERT INTO lorem VALUES (?)') for (var i = 0; i < 10; i++) { - stmt.run('Ipsum ' + i); + stmt.run('Ipsum ' + i) } - stmt.finalize(); + stmt.finalize() - db.each('SELECT rowid AS id, info FROM lorem', function(err, row) { - console.log(row.id + ': ' + row.info); - }); -}); + db.each('SELECT rowid AS id, info FROM lorem', function (err, row) { + console.log(row.id + ': ' + row.info) + }) +}) -db.close(); +db.close() ``` @@ -345,10 +350,10 @@ $ npm install elasticsearch **Example** ```js -var elasticsearch = require('elasticsearch'); +var elasticsearch = require('elasticsearch') var client = elasticsearch.Client({ host: 'localhost:9200' -}); +}) client.search({ index: 'books', @@ -361,10 +366,10 @@ client.search({ } } } -}).then(function(response) { - var hits = response.hits.hits; -}, function(error) { - console.trace(error.message); -}); +}).then(function (response) { + var hits = response.hits.hits +}, function (error) { + console.trace(error.message) +}) ``` diff --git a/en/guide/error-handling.md b/en/guide/error-handling.md index d17e0b86b5..2dcff76e95 100755 --- a/en/guide/error-handling.md +++ b/en/guide/error-handling.md @@ -13,26 +13,26 @@ except error-handling functions have four arguments instead of three: `(err, req, res, next)`. For example: ```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!') +}) ``` You define error-handling middleware last, after other `app.use()` and routes calls; for example: ```js -var bodyParser = require('body-parser'); -var methodOverride = require('method-override'); +var bodyParser = require('body-parser') +var methodOverride = require('method-override') app.use(bodyParser.urlencoded({ - extended: true -})); -app.use(bodyParser.json()); -app.use(methodOverride()); -app.use(function(err, req, res, next) { + extended: true +})) +app.use(bodyParser.json()) +app.use(methodOverride()) +app.use(function (err, req, res, next) { // logic -}); +}) ``` 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. @@ -43,26 +43,26 @@ regular middleware functions. For example, if you wanted to define an error-hand for requests made by using `XHR`, and those without, you might use the following commands: ```js -var bodyParser = require('body-parser'); -var methodOverride = require('method-override'); +var bodyParser = require('body-parser') +var methodOverride = require('method-override') app.use(bodyParser.urlencoded({ - extended: true -})); -app.use(bodyParser.json()); -app.use(methodOverride()); -app.use(logErrors); -app.use(clientErrorHandler); -app.use(errorHandler); + extended: true +})) +app.use(bodyParser.json()) +app.use(methodOverride()) +app.use(logErrors) +app.use(clientErrorHandler) +app.use(errorHandler) ``` In this example, the generic `logErrors` might write request and error information to `stderr`, for example: ```js -function logErrors(err, req, res, next) { - console.error(err.stack); - next(err); +function logErrors (err, req, res, next) { + console.error(err.stack) + next(err) } ``` @@ -71,11 +71,11 @@ Also in this example, `clientErrorHandler` is defined as follows; in this case, Notice that when _not_ calling "next" in an error-handling function, you are responsible for writing (and ending) the response. Otherwise those requests will "hang" and will not be eligible for garbage collection. ```js -function clientErrorHandler(err, req, res, next) { +function clientErrorHandler (err, req, res, next) { if (req.xhr) { - res.status(500).send({ error: 'Something failed!' }); + res.status(500).send({ error: 'Something failed!' }) } else { - next(err); + next(err) } } ``` @@ -83,9 +83,9 @@ function clientErrorHandler(err, req, res, next) { The "catch-all" `errorHandler` function might be implemented as follows: ```js -function errorHandler(err, req, res, next) { - res.status(500); - res.render('error', { error: err }); +function errorHandler (err, req, res, next) { + res.status(500) + res.render('error', { error: err }) } ``` @@ -95,18 +95,17 @@ If you have a route handler with multiple callback functions you can use the `ro ```js app.get('/a_route_behind_paywall', - function checkIfPaidSubscriber(req, res, next) { - if(!req.user.hasPaid) { - + function checkIfPaidSubscriber (req, res, next) { + if (!req.user.hasPaid) { // continue handling this request - next('route'); + next('route') } - }, function getPaidContent(req, res, next) { - PaidContent.find(function(err, doc) { - if(err) return next(err); - res.json(doc); - }); - }); + }, function getPaidContent (req, res, next) { + PaidContent.find(function (err, doc) { + if (err) return next(err) + res.json(doc) + }) + }) ``` 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. @@ -137,12 +136,12 @@ the default error handling mechanisms in Express, when the headers have already been sent to the client: ```js -function errorHandler(err, req, res, next) { +function errorHandler (err, req, res, next) { if (res.headersSent) { - return next(err); + return next(err) } - res.status(500); - res.render('error', { error: err }); + res.status(500) + res.render('error', { error: err }) } ``` diff --git a/en/guide/migrating-4.md b/en/guide/migrating-4.md index 3a832cb335..ccf9c7ec1e 100755 --- a/en/guide/migrating-4.md +++ b/en/guide/migrating-4.md @@ -101,10 +101,10 @@ In version 4 you can use a variable parameter to define the path where middlewar For example: ```js -app.use('/book/:id', function(req, res, next) { - console.log('ID:', req.params.id); - next(); -}); +app.use('/book/:id', function (req, res, next) { + console.log('ID:', req.params.id) + next() +}) ```

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 `
`: ### multiple format support ```js -var connect = require('connect') +var connect = require('connect') var methodOverride = require('method-override') // override with different headers; last one takes precedence @@ -138,15 +138,15 @@ You can implement any kind of custom logic with a function for the `getter`. The implements the logic for looking in `req.body` that was in `method-override@1`: ```js -var bodyParser = require('body-parser') -var connect = require('connect') +var bodyParser = require('body-parser') +var connect = require('connect') var methodOverride = require('method-override') // NOTE: when using req.body, you must fully parse the request body // before you call methodOverride() in your middleware stack, // otherwise req.body will not be populated. app.use(bodyParser.urlencoded()) -app.use(methodOverride(function(req, res){ +app.use(methodOverride(function (req, res) { if (req.body && typeof req.body === 'object' && '_method' in req.body) { // look in urlencoded POST bodies and delete it var method = req.body._method diff --git a/en/resources/middleware/morgan.md b/en/resources/middleware/morgan.md index 3b30ba9968..65ad6ac348 100644 --- a/en/resources/middleware/morgan.md +++ b/en/resources/middleware/morgan.md @@ -109,7 +109,7 @@ The minimal output. To define a token, simply invoke `morgan.token()` with the name and a callback function. This callback function is expected to return a string value. The value returned is then available as ":type" in this case: ```js -morgan.token('type', function(req, res){ return req.headers['content-type']; }) +morgan.token('type', function (req, res) { return req.headers['content-type'] }) ``` Calling `morgan.token()` using the same name as an existing token will overwrite that token definition. @@ -241,11 +241,12 @@ Simple app that will log all requests in the Apache combined format to the file var express = require('express') var fs = require('fs') var morgan = require('morgan') +var path = require('path') var app = express() // create a write stream (in append mode) -var accessLogStream = fs.createWriteStream(__dirname + '/access.log', {flags: 'a'}) +var accessLogStream = fs.createWriteStream(path.join(__dirname, 'access.log'), {flags: 'a'}) // setup the logger app.use(morgan('combined', {stream: accessLogStream})) @@ -266,9 +267,10 @@ var FileStreamRotator = require('file-stream-rotator') var express = require('express') var fs = require('fs') var morgan = require('morgan') +var path = require('path') var app = express() -var logDirectory = __dirname + '/log' +var logDirectory = path.join(__dirname, 'log') // ensure log directory exists fs.existsSync(logDirectory) || fs.mkdirSync(logDirectory) @@ -298,7 +300,7 @@ var express = require('express') var morgan = require('morgan') var uuid = require('node-uuid') -morgan.token('id', function getId(req) { +morgan.token('id', function getId (req) { return req.id }) @@ -311,7 +313,7 @@ app.get('/', function (req, res) { res.send('hello, world!') }) -function assignId(req, res, next) { +function assignId (req, res, next) { req.id = uuid.v4() next() } diff --git a/en/resources/middleware/multer.md b/en/resources/middleware/multer.md index 9eb6492810..4458ede62c 100644 --- a/en/resources/middleware/multer.md +++ b/en/resources/middleware/multer.md @@ -28,7 +28,7 @@ Basic usage example: ```javascript var express = require('express') -var multer = require('multer') +var multer = require('multer') var upload = multer({ dest: 'uploads/' }) var app = express() @@ -60,7 +60,7 @@ In case you need to handle a text-only multipart form, you can use any of the mu ```javascript var express = require('express') var app = express() -var multer = require('multer') +var multer = require('multer') var upload = multer() app.post('/profile', upload.array(), function (req, res, next) { @@ -241,7 +241,6 @@ should be skipped. The function should look like this: ```javascript function fileFilter (req, file, cb) { - // The function should call `cb` with a boolean // to indicate if the file should be accepted @@ -253,7 +252,6 @@ function fileFilter (req, file, cb) { // You can always pass an error if something goes wrong: cb(new Error('I don\'t have a clue!')) - } ``` diff --git a/en/resources/middleware/serve-favicon.md b/en/resources/middleware/serve-favicon.md index 437a007c24..f4c6058a4e 100644 --- a/en/resources/middleware/serve-favicon.md +++ b/en/resources/middleware/serve-favicon.md @@ -70,29 +70,31 @@ to avoid processing any other middleware if we already know the request is for ### express ```javascript -var express = require('express'); -var favicon = require('serve-favicon'); +var path = require('path') +var express = require('express') +var favicon = require('serve-favicon') -var app = express(); -app.use(favicon(__dirname + '/public/favicon.ico')); +var app = express() +app.use(favicon(path.join(__dirname, '/public/favicon.ico'))) // Add your routes here, etc. -app.listen(3000); +app.listen(3000) ``` ### connect ```javascript -var connect = require('connect'); -var favicon = require('serve-favicon'); +var path = require('path') +var connect = require('connect') +var favicon = require('serve-favicon') -var app = connect(); -app.use(favicon(__dirname + '/public/favicon.ico')); +var app = connect() +app.use(favicon(path.join(__dirname, '/public/favicon.ico'))) // Add your middleware here, etc. -app.listen(3000); +app.listen(3000) ``` ### vanilla http server @@ -101,26 +103,27 @@ This middleware can be used anywhere, even outside express/connect. It takes `req`, `res`, and `callback`. ```javascript -var http = require('http'); -var favicon = require('serve-favicon'); -var finalhandler = require('finalhandler'); +var http = require('http') +var path = require('path') +var favicon = require('serve-favicon') +var finalhandler = require('finalhandler') -var _favicon = favicon(__dirname + '/public/favicon.ico'); +var _favicon = favicon(path.join(__dirname, '/public/favicon.ico')) -var server = http.createServer(function onRequest(req, res) { - var done = finalhandler(req, res); +var server = http.createServer(function onRequest (req, res) { + var done = finalhandler(req, res) - _favicon(req, res, function onNext(err) { - if (err) return done(err); + _favicon(req, res, function onNext (err) { + if (err) return done(err) // continue to process the request here, etc. - res.statusCode = 404; - res.end('oops'); - }); -}); + res.statusCode = 404 + res.end('oops') + }) +}) -server.listen(3000); +server.listen(3000) ``` ## License diff --git a/en/resources/middleware/serve-index.md b/en/resources/middleware/serve-index.md index 41641c1b6f..297ebdbd8d 100644 --- a/en/resources/middleware/serve-index.md +++ b/en/resources/middleware/serve-index.md @@ -111,9 +111,9 @@ var index = serveIndex('public/ftp', {'icons': true}) var serve = serveStatic('public/ftp') // Create server -var server = http.createServer(function onRequest(req, res){ +var server = http.createServer(function onRequest (req, res) { var done = finalhandler(req, res) - serve(req, res, function onNext(err) { + serve(req, res, function onNext (err) { if (err) return done(err) index(req, res, done) }) @@ -126,7 +126,7 @@ server.listen(3000) ### Serve directory indexes with express ```js -var express = require('express') +var express = require('express') var serveIndex = require('serve-index') var app = express() diff --git a/en/resources/middleware/serve-static.md b/en/resources/middleware/serve-static.md index c2f0d8b412..15d8c58916 100644 --- a/en/resources/middleware/serve-static.md +++ b/en/resources/middleware/serve-static.md @@ -163,7 +163,7 @@ var serve = serveStatic('public/ftp', { }) // Set header to force download -function setHeaders(res, path) { +function setHeaders (res, path) { res.setHeader('Content-Disposition', contentDisposition(path)) } @@ -204,8 +204,8 @@ var serveStatic = require('serve-static') var app = express() -app.use(serveStatic(__dirname + '/public-optimized')) -app.use(serveStatic(__dirname + '/public')) +app.use(serveStatic(path.join(__dirname, 'public-optimized'))) +app.use(serveStatic(path.join(__dirname, 'public'))) app.listen(3000) ``` @@ -221,7 +221,7 @@ var serveStatic = require('serve-static') var app = express() -app.use(serveStatic(__dirname + '/public', { +app.use(serveStatic(path.join(__dirname, 'public'), { maxAge: '1d', setHeaders: setCustomCacheControl })) diff --git a/en/resources/middleware/session.md b/en/resources/middleware/session.md index 0a784dcb09..2768c8ef19 100644 --- a/en/resources/middleware/session.md +++ b/en/resources/middleware/session.md @@ -180,7 +180,7 @@ The default value is a function which uses the `uid-safe` library to generate ID ```js app.use(session({ - genid: function(req) { + genid: function (req) { return genuuid() // use UUIDs for session IDs }, secret: 'keyboard cat' @@ -293,10 +293,10 @@ are typically fine. For example below is a user-specific view counter: ```js // Use the session middleware -app.use(session({ secret: 'keyboard cat', cookie: { maxAge: 60000 }})) +app.use(session({ secret: 'keyboard cat', cookie: { maxAge: 60000 } })) // Access the session as req.session -app.get('/', function(req, res, next) { +app.get('/', function (req, res, next) { var sess = req.session if (sess.views) { sess.views++ @@ -317,7 +317,7 @@ To regenerate the session simply invoke the method. Once complete, a new SID and `Session` instance will be initialized at `req.session`. ```js -req.session.regenerate(function(err) { +req.session.regenerate(function (err) { // will have a new session here }) ``` @@ -327,7 +327,7 @@ req.session.regenerate(function(err) { Destroys the session, removing `req.session`; will be re-generated next request. ```js -req.session.destroy(function(err) { +req.session.destroy(function (err) { // cannot access session here }) ``` @@ -337,7 +337,7 @@ req.session.destroy(function(err) { Reloads the session data. ```js -req.session.reload(function(err) { +req.session.reload(function (err) { // session updated }) ``` @@ -357,7 +357,7 @@ There are some cases where it is useful to call this method, for example, long- lived requests or in WebSockets. ```js -req.session.save(function(err) { +req.session.save(function (err) { // session saved }) ``` diff --git a/en/resources/middleware/timeout.md b/en/resources/middleware/timeout.md index 8197e7c7b0..0d62432e2f 100644 --- a/en/resources/middleware/timeout.md +++ b/en/resources/middleware/timeout.md @@ -76,83 +76,83 @@ care to check if the request has timedout before you continue to act on the request. ```javascript -var express = require('express'); -var timeout = require('connect-timeout'); +var express = require('express') +var timeout = require('connect-timeout') // example of using this top-level; note the use of haltOnTimedout // after every middleware; it will stop the request flow on a timeout -var app = express(); -app.use(timeout('5s')); -app.use(bodyParser()); -app.use(haltOnTimedout); -app.use(cookieParser()); -app.use(haltOnTimedout); +var app = express() +app.use(timeout('5s')) +app.use(bodyParser()) +app.use(haltOnTimedout) +app.use(cookieParser()) +app.use(haltOnTimedout) // Add your routes here, etc. -function haltOnTimedout(req, res, next){ - if (!req.timedout) next(); +function haltOnTimedout (req, res, next) { + if (!req.timedout) next() } -app.listen(3000); +app.listen(3000) ``` ### express 3.x ```javascript -var express = require('express'); -var bodyParser = require('body-parser'); -var timeout = require('connect-timeout'); - -var app = express(); -app.post('/save', timeout('5s'), bodyParser.json(), haltOnTimedout, function(req, res, next){ - savePost(req.body, function(err, id){ - if (err) return next(err); - if (req.timedout) return; - res.send('saved as id ' + id); - }); -}); - -function haltOnTimedout(req, res, next){ - if (!req.timedout) next(); +var express = require('express') +var bodyParser = require('body-parser') +var timeout = require('connect-timeout') + +var app = express() +app.post('/save', timeout('5s'), bodyParser.json(), haltOnTimedout, function (req, res, next) { + savePost(req.body, function (err, id) { + if (err) return next(err) + if (req.timedout) return + res.send('saved as id ' + id) + }) +}) + +function haltOnTimedout (req, res, next) { + if (!req.timedout) next() } -function savePost(post, cb){ - setTimeout(function(){ - cb(null, ((Math.random()* 40000) >>> 0)); - }, (Math.random()* 7000) >>> 0)); +function savePost (post, cb) { + setTimeout(function () { + cb(null, ((Math.random() * 40000) >>> 0)) + }, ((Math.random() * 7000) >>> 0)) } -app.listen(3000); +app.listen(3000) ``` ### connect ```javascript -var bodyParser = require('body-parser'); -var connect = require('connect'); -var timeout = require('connect-timeout'); - -var app = require('connect'); -app.use('/save', timeout('5s'), bodyParser.json(), haltOnTimedout, function(req, res, next){ - savePost(req.body, function(err, id){ - if (err) return next(err); - if (req.timedout) return; - res.send('saved as id ' + id); - }); -}); - -function haltOnTimedout(req, res, next){ - if (!req.timedout) next(); +var bodyParser = require('body-parser') +var connect = require('connect') +var timeout = require('connect-timeout') + +var app = require('connect') +app.use('/save', timeout('5s'), bodyParser.json(), haltOnTimedout, function (req, res, next) { + savePost(req.body, function (err, id) { + if (err) return next(err) + if (req.timedout) return + res.send('saved as id ' + id) + }) +}) + +function haltOnTimedout (req, res, next) { + if (!req.timedout) next() } -function savePost(post, cb){ - setTimeout(function(){ - cb(null, ((Math.random()* 40000) >>> 0)); - }, (Math.random()* 7000) >>> 0)); +function savePost (post, cb) { + setTimeout(function () { + cb(null, ((Math.random() * 40000) >>> 0)) + }, ((Math.random() * 7000) >>> 0)) } -app.listen(3000); +app.listen(3000) ``` ## License diff --git a/en/resources/middleware/vhost.md b/en/resources/middleware/vhost.md index a694c54fe0..9ff39f041b 100644 --- a/en/resources/middleware/vhost.md +++ b/en/resources/middleware/vhost.md @@ -98,7 +98,7 @@ var mainapp = connect() // create app that will server user content from public/{username}/ var userapp = connect() -userapp.use(function(req, res, next){ +userapp.use(function (req, res, next) { var username = req.vhost[0] // username is the "*" // pretend request was for /{username}/* for file serving diff --git a/en/starter/basic-routing.md b/en/starter/basic-routing.md index 6d5e1704e1..bd2fc639b5 100755 --- a/en/starter/basic-routing.md +++ b/en/starter/basic-routing.md @@ -35,32 +35,32 @@ Respond with `Hello World!` on the homepage: ```js app.get('/', function (req, res) { - res.send('Hello World!'); -}); + res.send('Hello World!') +}) ``` Respond to POST request on the root route (`/`), the application's home page: ```js app.post('/', function (req, res) { - res.send('Got a POST request'); -}); + res.send('Got a POST request') +}) ``` Respond to a PUT request to the `/user` route: ```js app.put('/user', function (req, res) { - res.send('Got a PUT request at /user'); -}); + res.send('Got a PUT request at /user') +}) ``` Respond to a DELETE request to the `/user` route: ```js app.delete('/user', function (req, res) { - res.send('Got a DELETE request at /user'); -}); + res.send('Got a DELETE request at /user') +}) ``` For more details about routing, see the [routing guide](/{{ page.lang }}/guide/routing.html). diff --git a/en/starter/faq.md b/en/starter/faq.md index ec307ecc36..14022d385f 100755 --- a/en/starter/faq.md +++ b/en/starter/faq.md @@ -59,9 +59,9 @@ do is add a middleware function at the very bottom of the stack (below all other to handle a 404 response: ```js -app.use(function(req, res, next) { - res.status(404).send('Sorry cant find that!'); -}); +app.use(function (req, res, next) { + res.status(404).send('Sorry cant find that!') +}) ``` ## How do I setup an error handler? @@ -70,10 +70,10 @@ 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 -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 more information, see [Error handling](/{{ page.lang }}/guide/error-handling.html). diff --git a/en/starter/hello-world.md b/en/starter/hello-world.md index 223f6cdcaf..2b473272a8 100755 --- a/en/starter/hello-world.md +++ b/en/starter/hello-world.md @@ -17,16 +17,16 @@ 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 -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, function () { - console.log('Example app listening on port 3000!'); -}); + console.log('Example app listening on port 3000!') +}) ``` The app starts a server and listens on port 3000 for connections. The app responds with "Hello World!" for requests diff --git a/en/starter/static-files.md b/en/starter/static-files.md index 72bc0772b7..46c1fd21a1 100755 --- a/en/starter/static-files.md +++ b/en/starter/static-files.md @@ -13,7 +13,7 @@ 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, use the following code to serve images, CSS files, and JavaScript files in a directory named `public`: ```js -app.use(express.static('public')); +app.use(express.static('public')) ``` Now, you can load the files that are in the `public` directory: @@ -33,8 +33,8 @@ Express looks up the files relative to the static directory, so the name of the To use multiple static assets directories, call the `express.static` middleware function multiple times: ```js -app.use(express.static('public')); -app.use(express.static('files')); +app.use(express.static('public')) +app.use(express.static('files')) ``` Express looks up the files in the order in which you set the static directories with the `express.static` middleware function. @@ -42,7 +42,7 @@ Express looks up the files in the order in which you set the static directories To create a virtual path prefix (where the path does not actually exist in the file system) for files that are served by the `express.static` function, [specify a mount path](/{{ page.lang }}/4x/api.html#app.use) for the static directory, as shown below: ```js -app.use('/static', express.static('public')); +app.use('/static', express.static('public')) ``` Now, you can load the files that are in the `public` directory from the `/static` path prefix. @@ -58,6 +58,6 @@ http://localhost:3000/static/hello.html However, the path that you provide to the `express.static` function is relative to the directory from where you launch your `node` process. If you run the express app from another directory, it's safer to use the absolute path of the directory that you want to serve: ```js -app.use('/static', express.static(__dirname + '/public')); +app.use('/static', express.static(path.join(__dirname, 'public'))) ```
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 + } + } +}