LoginSignup
30
31

More than 5 years have passed since last update.

Expressことはじめ

Last updated at Posted at 2015-10-24
  • node.jsを利用したwebアプリケーション・フレームワーク
  • 今回はExpress3を使用します
  • 前提としてnode.jsがインストールされていること

exressインストール(グローバルにインストール)

# バージョンを指定してインストールしないと、最新のバージョン4系がインストールされてしまう
$ sudo npm install -g express@3.x.x

プロジェクトの作成

今回はサンプルプロジェクトを使用せず、最初から作成していきます

プロジェクトを作りたいディレクトリにて下記を実行

# package.jsonを作成
$ npm init
# package.jsonに登録するために--save-devオプションを指定
$ npm install express@3.x.x --save-dev

app.jsを作成

app.js
var express = require('express'),
    app = express();

app.use(app.router);


// トップ画面
app.get('/', function(req, res) {
    res.send('hello world');
});

// "/about"でアクセスしてきた時の処理
app.get('/about', function(req, res) {
    res.send('about this page');
});

// 3000ポートで待ち受ける
app.listen(3000);
console.log('server starting...');

起動

$ node app.js
> server starting...

下記にアクセスするとhello worldが表示される
http://localhost:3000/

middleware

  • app.jsのapp.use()の部分のこと
  • リクエストが来てからの処理を上から順次実行していく
app.use(app.router);

カスタムmiddleware

app.user(function(req, res, next) {
    console.log('custom middleware');
    next(); // 今の処理が終わったら次にいく
});

参考
http://qiita.com/kazusa-qooq/items/23926befcb87c0c7b26f

logger

便利なログ機能

app.use(express.logger('dev'));

nodemon

ファイルを監視して自動で再起動してくれます

インストール

$ npm install nodemon -g

使い方
nodeコマンドの代わりにつかう

$ nodemon app.js

テンプレートファイルを使用する(ejs)

テンプレートエンジンのejsを使用します

インストール

$ npm install ejs --save-dev

viewa/index.htmlを作成します

index.html
<html>
    <h1><%= title %></h1>
    <p>hello from ejs</p>
</html>
app.js

...
// ejsを使用するための設定
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');

...

app.get('/', function(req, res) {
    // index.ejsの拡張子は省略可能
    res.render('index', {title : 'タイトル'});
});
...

POSTメソッドに対応させる

index.htmlにフォームを追加します

index.html
<html>
    <form method="post" action="/create">
        <input type="text" name="name">
        <input type="submit" value="create">
    </form>
</html>

postに対応させるためのmiddlewareを指定して、処理を書く

app.js

...
// postを使用するための設定
app.use(express.json());
app.use(express.urlencoded());

...

app.post('/create', function(req, res) {
    console.log(req.body);
    res.send(req.body.name);
});
...

実行すると、フォームで書いたテキストが表示されます

30
31
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
30
31