「入門Node.jsプログラミング 」の感想・備忘録3

スポンサーリンク
「入門Node.jsプログラミング 」の感想・備忘録2の続き

Lesson11

エラー処理を追加する

  • HTTPステータスコードを定数として扱うためのパッケージをインストール。
    npm install http-status-codes
  • ミドルウェアで処理する行を追加する場合は、通常の経路よりも後に置く。
  • logErrorsはエラー情報をロギングするためのエラー処理ミドルウェア。
  • respondNoResourceFoundは404エラー画面表示用の通常経路。
  • respondInternalErrorは500エラー画面表示用のエラー処理ミドルウェア。
const errorController = require("./controllers/errorController");
// 〜省略〜
app.use(errorController.logErrors);
app.use(errorController.respondNoResourceFound);
app.use(errorController.respondInternalError);
const httpStatus = require("http-status-codes");

exports.logErrors = (error, req, res, next) => {
  console.error(error.stack);
  next(error);
};
exports.respondNoResourceFound = (req, res) => {
  res.status(httpStatus.NOT_FOUND);
  res.send(`${httpStatus.NOT_FOUND} | The page does not exist!`);
};
exports.respondInternalError = (error, req, res, next) => {
  console.log(`ERROR occurred: ${error.stack}`);
  res.status(httpStatus.INTERNAL_SERVER_ERROR);
  res.send(`${httpStatus.INTERNAL_SERVER_ERROR} | Sorry, our application is experiencing a problem!`);
};
// 引数4つのミドルウェア関数はにするとエラー処理とみなされる。

静的ファイルの供給

  • index.jsにapp.use(express.static("public"));を追加する。
    これだけでpublc/hoge.jpgにhttp://localhost:3000/hoge.jpgでアクセスできるようになる。

Lesson12

Expressアプリの作成

  • ここまでのまとめとしてExpressを使ったWEBアプリを作成する。

1. アプリの初期化

  1. npm init
  2. npm install express ejs express-ejs-layouts http-status-codes

2. index.jsの作成

'use strict';

const express = require('express');
const app = express();
app.set('port', process.env.PORT || 3000);
app.set("view engine", "ejs");
app.use(
  express.urlencoded({
    extended: false
  })
);
app.use(express.json());
app.use(express.static("public"));

app.get('/', (req, res) => {
  res.render('index');
});

app.listen(app.get('port'), () => {
  console.log(`Server running at http://localhost:${app.get('port')}`);
});
// ここまででviews/index.ejsが表示される。

3. 経路を追加

const homeController = require("./controllers/homeController");
// と
app.get("/courses", homeController.showCourses);
app.get("/contact", homeController.showSignUp);
app.post("/contact", homeController.postedSignUpForm);
// をindex.jsに追加。

4. homeController.jsの作成

'use strict';

const courses = [
  {
    title: 'Event Driven Cakes',
    cost: 50
  },
  {
    title: 'Asynchronous Artichoke',
    cost: 25
  },
];

exports.showCourses = (req, res) => {
  res.render('courses', {
    offeredCourses: courses
  });
};

exports.showSignUp = (req, res) => {
  res.render('contact');
};

exports.postedSignUpForm = (req, res) => {
  res.render('thanks');
};

5. ビューの作成

const layouts = require("express-ejs-layouts");
app.use(layouts);
// をindex.jsに追加。
<%- body %>
<h1>index</h1>
<p><a href="/courses">courses</a></p>
<p><a href="/contact">contact</a></p>
<img src="/hoge.jpg">
<h1>Our Courses</h1>
<% offeredCourses.forEach(course => { %>
<h3><%= course.title %> : <%= course.cost %></h3>
<% }); %>
<form action="/contact" method="post">
  <p>Name : <input type="text" name="name" value=""></p>
  <p>Email : <input type="email" name="email" value=""></p>
  <p><input class="button" type="submit" value="submit"></p>
</form>

コメント