回答編集履歴
2
routerに合わせた記述に変更
answer
CHANGED
@@ -3,13 +3,16 @@
|
|
3
3
|
リクエストを捌くものはエンドポイントやコントローラといったロールになります。
|
4
4
|
|
5
5
|
従ってディレクトリ構成はこんな感じになるはずです。
|
6
|
+
今回はrouterを使っているので、routesというディレクトリに突っ込んでみました。
|
6
7
|
|
7
8
|
```
|
9
|
+
- app.js
|
8
|
-
|
10
|
+
- router/
|
11
|
+
- index.js
|
9
|
-
-
|
12
|
+
- routes/
|
10
13
|
- index.js
|
11
|
-
|
14
|
+
- views/
|
12
|
-
|
15
|
+
- index.ejs
|
13
16
|
```
|
14
17
|
|
15
18
|
---
|
@@ -32,26 +35,28 @@
|
|
32
35
|
```JavaScript
|
33
36
|
// app.js
|
34
37
|
const express = require('express');
|
35
|
-
const
|
38
|
+
const router = require('./router');
|
36
39
|
const app = express();
|
40
|
+
const router(app);
|
37
41
|
|
38
|
-
//
|
42
|
+
// router/index.js
|
43
|
+
module.exports = app =>
|
39
|
-
readdir(`${__dirname}/endpoints`)
|
44
|
+
readdir(`${__dirname}/endpoints`)
|
40
|
-
|
45
|
+
.filter(it => /¥.js$/.test(it))
|
41
|
-
|
46
|
+
.map(it => it.replace(/¥.js$/, ''))
|
42
|
-
|
47
|
+
.forEach(name => {
|
43
|
-
|
48
|
+
const endpoint = require(`./endpoints/${name}.js`);
|
44
|
-
|
49
|
+
if (endpoint.get) {
|
45
|
-
|
50
|
+
app.get(name, endpoint.get);
|
46
|
-
|
51
|
+
}
|
47
|
-
|
52
|
+
if (endpoint.post) {
|
48
|
-
|
53
|
+
app.post(name, endpoint.post);
|
49
|
-
|
54
|
+
}
|
50
|
-
|
55
|
+
})
|
51
56
|
|
52
|
-
//
|
57
|
+
// router/routes/index.js
|
53
58
|
module.exports = {
|
54
|
-
get: function (req, res) {
|
59
|
+
get: function (req, res, next) {
|
55
60
|
res.render('/index', {title: 'Express'});
|
56
61
|
}
|
57
62
|
}
|
1
endpoints変数は使わないので削除
answer
CHANGED
@@ -1,5 +1,6 @@
|
|
1
1
|
そのindex.jsは少なくともViewではありません。
|
2
|
-
Viewとは、「私に値を投げ込んだら、その値に応じたHTMLを自動生成するよ!」というものであり、
|
2
|
+
Viewとは、「私に値を投げ込んだら、その値に応じたHTMLを自動生成するよ!」というものであり、
|
3
|
+
リクエストを捌くものはエンドポイントやコントローラといったロールになります。
|
3
4
|
|
4
5
|
従ってディレクトリ構成はこんな感じになるはずです。
|
5
6
|
|
@@ -34,7 +35,8 @@
|
|
34
35
|
const readdir = require('fs-readdir-recursive');
|
35
36
|
const app = express();
|
36
37
|
|
38
|
+
// 再帰的にendpointsディレクトリ配下のjsを読み込んでappに登録していく
|
37
|
-
|
39
|
+
readdir(`${__dirname}/endpoints`)
|
38
40
|
.filter(it => /¥.js$/.test(it))
|
39
41
|
.map(it => it.replace(/¥.js$/, ''))
|
40
42
|
.forEach(name => {
|