logo

Express.js

Route

In app.js

var routes = require('./routes');

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

In routes/index.js

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

Enable CORS

If you see error like:

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

Add the followings to the app.js:

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

req.params.<param_name>

E.g. in app.js:

app.get('/foo/:name', ...)

A request to /foo/bar will generate

req.params.name == 'bar';

File Upload

Uploaded files

req.files.<file_name>.path

Data Upload

Uploaded data

req.body.<data_name>

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
app.route('/page/:name').get(function (req, res) {
  res.render('partials/' + req.params.name);
});

Multer

File Upload

https://github.com/expressjs/multer

Auto reload in development

Use Automon:

$ npm install -g nodemon

Then use nodemon instead of node when starting the app:

$ nodemon app.js