FORSMILE
JA
開発記事2016/01/28

[Node.js] Building a Server with Node.js and Express

Running Aurelia.js in a Node.js and Express Environment - Part 3

Back to Blog

Running Aurelia.js in a Node.js and Express Environment - Part 3

Running Aurelia.js in a Node.js and Express Environment - Part 1

Running Aurelia.js in a Node.js and Express Environment - Part 2

In Part 1 and Part 2, we ran Aurelia.js in a local environment and created the production bundle files.

This time, I'd like to implement Express, a web application framework for Node.js.

Ultimately, we will be uploading the files to a cloud application platform called Heroku, so the explanation will be based on that premise.

INSTALLING EXPRESS

Reference: [Node.js] Installing Node.js and a brief explanation of how to use npm

Add it to the dependencies in package.json using npm.

bash
npm install express --save

Express application generator (Not used this time)

→ Express application generator

Using the generator allows for easy Express setup.

INSTALLING SERVER MODULES

Install basic web feature modules to be used with Express.

bash
npm install body-parser --save
npm install cookie-parser --save
npm install swig --save

SETTING UP app.js

You can name it anything, but create a .js file to start the server.

javascript
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var swig = require('swig');

var app = express();

var allowCrossDomain = function(req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
    res.header('Access-Control-Allow-Headers', 'Content-Type');
    next();
};

// view engine setup
app.engine('html', swig.renderFile);
app.set('view engine', 'html');
app.set('views', path.join(__dirname, 'views'));

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(allowCrossDomain);
app.use(cookieParser());
app.use(express.static(path.join(__dirname, '/')));

var routes = require('./routes/index');
app.use('/', routes);

app.set('port', process.env.PORT || 5000);

var server = app.listen(app.get('port'), function() {
  var host = server.address().address;
  var port = server.address().port;
  console.log('Example app listening at http://%s:%s', host, port);
});

A brief explanation of app.js

javascript
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var swig = require('swig');

var app = express();

Each module is called to set up the Express execution environment.

There's a new module called 'path', which is a utility in Node.js for handling file paths.

javascript
var allowCrossDomain = function(req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
    res.header('Access-Control-Allow-Headers', 'Content-Type');
    next();
};

Reference for CORS: HTTP access control (CORS)|MDN

text
// view engine setup
app.engine('html', swig.renderFile);
app.set('view engine', 'html');
app.set('views', path.join(__dirname, 'views'));

This is the template engine configuration. Here, it specifies that templates will be placed in the 'views' folder.

css
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(allowCrossDomain);
app.use(cookieParser());
app.use(express.static(path.join(__dirname, '/')));

Middleware functions are mounted using app.use.

File paths for static files (such as JS, CSS, or files called from HTML) can also be specified here.

javascript
var routes = require('./routes/index');
app.use('/', routes);

index.js, specified by the path, is loaded as a module. (We'll create index.js later.)

javascript
app.set('port', process.env.PORT || 5000);

var server = app.listen(app.get('port'), function() {
  var host = server.address().address;
  var port = server.address().port;
  console.log('Example app listening at http://%s:%s', host, port);
});

SETTING UP index.js

Create index.js, which is called by the routes in app.js. We'll keep it simple, as we just need index.html to be displayed.

index.js

javascript
var express = require('express');
var router = express.Router();

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index');
});

module.exports = router;

MOVING index.html

Since app.js specifies the 'views' folder as the location for files to be displayed, create a 'views' folder and place index.html inside it.

If you also need to rewrite the gulp path, modify the path to index in the following file:

javascript
gulp.task('serve', ['build'], function(done) {
  browserSync({
    online: false,
    open: false,
    port: 9000,
    server: {
      baseDir: ['.'],
      index: "views/index.html",
      middleware: function(req, res, next) {
        res.setHeader('Access-Control-Allow-Origin', '*');
        next();
      }
    }
  }, done);
});

STARTUP

text
node app.js

Try accessing the following address from your browser. If Aurelia is displayed, you're done.

text
http://localhost:5000/
📦
Amazon で関連書籍・ツールを検索
web development programming book
Amazonで探す →(アソシエイトリンク)