Express.js

Route

In app.js

#!javascript
var routes = require('./routes');

app.get('/loadData/:name', routes.loadData);

In routes/index.js

#!javascript
exports.loadData = function(req, res) {
    console.log(req.route.params.name)
    // or
    console.log(req.params.name)
}

In browser

http://127.0.0.1:3000/loaddata/foo

In terminal

foo

Create a New Project

#!javascript
$ express --sessions --css less --ejs 

Enable CORS

If you see error like:

XMLHttpRequest cannot load . No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '' is therefore not allowed access.

Add the followings to the app.js:

#!javascript
app.all('*', function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    next();
});

Req Lookup

Params

In Express 4:

Params are stored as

#!javascript
req.params.

E.g. in app.js:

#!javascript
app.get('/foo/:name', ...)

A request to /foo/bar will generate

#!javascript
req.params.name == 'bar'

File Upload

Uploaded files

#!javascript
req.files..path

Data Upload

Uploaded data

#!javascript
req.body.

req.files and req.body are available for POST requests, but not GET requests

Serve Route Based on File Structure

To serve multi-player routes and map to files in arbitrary folder hierarchy, e.g.

  • http://www.example.com/page/a to partial/a.html

  • http://www.example.com/page/b/c to partial/b/c.html

  • http://www.example.com/page/d/e/f to partial/d/e/f.html

    !javascript

    app.route('/page/:name').get(function(req, res) { res.render('partials/' + req.params.name); })

Multer

File Upload

https://github.com/expressjs/multer