LoginSignup
2
1

More than 5 years have passed since last update.

express使い方

Posted at

前提:nodejs,npmが使える状態であること。

express環境構築

1.workspaceを作りたい場所の一段上で実行
express -e testsite
2.必要なものを自動インストール(たぶん、ejsやfsも勝手に生成される?)
cd testsite && npm install
3.実行できるか確かめる
node ./bin/www

※上記を実行後に、http://localhost:3000/ へアクセス

expressの基本工程

あるurlをたたいた時に、"出力されるejsファイル"と"その引数"を決定していく工程。

1.testsite/app.jsにルーティングを書く。(似たようなものがある所に書けば管理しやすい)
var maincontentsRouter = require('./routes/maincontents');
var gamecontentsRouter = require('./routes/gamecontents');
app.use('/maincontents',maincontentsRouter);
app.use('/gamecontents',gamecontentsRouter);

※ここでは、urlとjsの関連付けを行っている。(.jsは省略してよい)

2.testsite/routes/にmaincontents.jsを作成し、以下のように編集
maincontens.js
var express = require('express');
var router = express.Router();
var fs = require('fs');
var ejs = require('ejs');
var maincontents = fs.readFileSync('./views/maincontents.ejs', 'utf8');
/* GET page. */
router.get('/', function(req, res, next) {
        res.render('template', 
        {
            title: 'main contents title',
        content:ejs.render(maincontents,{
        })
        }
    );
});
module.exports = router;

※ここではejsファイルを読み込んでいる。testsite/routes/に置かれているjsファイルは、ejsの読み込みと読み込み時に渡す変数内の値の決定が主な役割。

3.testsite/routes/にgamecontents.jsを作成し,上記を参考に編集。

※mainをgameに置換するだけ。

4.testsite/views/template.ejsを作る。
template.ejs
<!doctype html>
<html lang="ja">
<head>
<meta charset="utf-8">
<html>
    <head>
    <title><%= title %></title>
</head>
<body>
<a href="/maincontents">home</a>
<a href="/gamecontents">game</a>
<p><%-content %></p>
</body>
</html>
5.testsite/views/maincontents.ejsを作る。
maincontents.ejs
<p>main contents</p>
6.testsite/views/gamecontents.ejsを作る。
maincontents.ejs
<p>game contents</p>
7.node bin/wwwで実行して確認してみる。

これで動けばok

2
1
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
2
1