LoginSignup
96
103

More than 5 years have passed since last update.

node.jsの勉強(express4)

Last updated at Posted at 2014-04-26

expressのインストール

expressのインストール管理者権限で実行しないとエラーになった。sudoで

コンソール
sudo npm install -g express

アプリケーションのテンプレートを作成
(アプリを作るディレクトリの親にて、アプリケーション名を指定してexpress)

これは、ejsを使う場合

コンソール
express -t ejs {アプリのフォルダ名}

【修正】バージョン3以降でejsを使う場合は、

コンソール
express -e {アプリのフォルダ名}

だった。

アプリのディレクトリに移動してモジュールの依存インストール

コンソール
cd {アプリのフォルダ名}
npm install -d

実行。
起動しない。。。

コンソール
node app.js

バージョンの確認

コンソール
express -V

package.jsonの中のscriptsを確認
startでサーバーが起動するようになっていた

  "scripts": {
    "start": "node ./bin/www"
  },

scriptsで設定したコマンドは
npm {コマンド}で実行できるみたい

これで起動

コンソール
npm start 

ブラウザで

http://localhost:3000/

見れた。

Express.png

終了は

control + c

gihyo.jp 基礎から学ぶNode.js メモ

基礎から学ぶNode.jsを見ながら、express4 & osx の環境で勉強したメモです。

ExpressでWebアプリの雛形を生成の読み替え

第3回 Express.jsを使ったWebアプリケーションを構築

EJSのひな形の設定がexpress4はこれだった

express -e firstapp

Express サーバー起動の読み替え

第3回 Express.jsを使ったWebアプリケーションを構築

node app.jsが反応しなかったので、これで起動

コンソール
npm start 

routesの設定を読み替え

第3回 Express.jsを使ったWebアプリケーションを構築

リクエストのバインドをどこに書けばいいか悩んで、
routes/index.js に書いた。

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

/* GET home page. */
var items = [
    { "text": "1st Post." }
    , { "text": "2nd Post." }
];

router.get('/', function(req, res) {
  res.render('index', { title: 'Entry List',items: items });
});


router.get('/form', function(req, res) {
    res.render('form', { title: 'New Entry' })
});

router.post('/create', function(req, res){
    console.log(req.body.text);
    res.redirect('/');
});

module.exports = router;


参考にしたサイト

基礎から学ぶNode.js

96
103
1

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
96
103