Node.js Express

設定

インストール

npm install -g express-generator

アプリの雛形作成

express --view=ejs sample

サーバー起動

node bin\www

※bin\www
var app = require(‘../app’);
var http = require(‘http’);

説明略
var port = normalizePort(process.env.PORT || ‘3000’);
app.set(‘port’, port);

var server = http.createServer(app);
server.listen(port);

ルーティング

./app.js
var indexRouter = require(‘./routes/index’);
var usersRouter = require(‘./routes/users’);

var app = express();

app.use(‘/’, indexRouter);
app.use(‘/users’, usersRouter);

※/routes/index.js
var express = require(‘express’);
var router = express.Router();

router.get(‘/’, function(req, res, next) {
 ~
});

module.exports = router;

View指定

設定

./app.js
app.set(‘views’, path.join(__dirname, ‘views’));

サーバー

※/routes/index.js
var express = require(‘express’);
var router = express.Router();

router.get(‘/’, function(req, res, next) {
 ./view/index.ejsを返す
 res.render(‘index’, { title: ‘Express’ });
});

module.exports = router;

リクエスト処理

GET

router.get(‘/get’, function(req, res, next) {
 let msg = req.query.msg;
 console.log(msg);
});

POST

router.post(‘/post’, function(req, res, next) {
 let msg = req.body[‘message‘];
 console.log(msg);
});

Node.js

前の記事

Node.js module