0
0

More than 3 years have passed since last update.

node.js超入門ノート3(Webページ追加編)

Last updated at Posted at 2021-08-15

Webページの追加

まずはテンプレートファイルを作成します。
viewsフォルダに以下のファイルを追加します。

hello.ejs
<!DOCTYPE html>
<html lang="ja">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="content-type" content="text/html">
        <title><%= title %></title>
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
    </head>
    <body class="container">
        <header>
            <h1><%= title %></h1>
        </header>
        <div role="main">
            <p><%- content %></p>
        </div>
    </body>
</html>

変数は以下のように指定します。

<%= 変数名 %>  HTML表記NG
<%- 変数名 %>  HTML表記OK

次にroutesフォルダに以下のソースコードを記載する。

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

/* GET home page. */
// 以下の'/'は後のapp.jsで示す/hello以降のアドレス
router.get('/', (req, res, next) => {
    var data = {
        title: 'Hello!',
        content: 'これは、サンプルのコンテンツです。<br>This is sample content.'
    };
    res.render('hello', data);
});

module.exports = router;

最後にhello.jsにアドレスを割り当てる。

app.js
// ルート用モジュールのロード
var hello = require('./routes/hello');
// アドレスに割り当てる
app.use('/hello', hello);

サーバーを起動し、以下のアドレスにアクセスする。

0
0
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
0
0