回答編集履歴

2

routerに合わせた記述に変更

2018/01/04 00:38

投稿

miyabi-sun
miyabi-sun

スコア21158

test CHANGED
@@ -8,19 +8,25 @@
8
8
 
9
9
  従ってディレクトリ構成はこんな感じになるはずです。
10
10
 
11
+ 今回はrouterを使っているので、routesというディレクトリに突っ込んでみました。
12
+
11
13
 
12
14
 
13
15
  ```
14
16
 
15
- app/
17
+ - app.js
16
18
 
19
+ - router/
20
+
21
+ - index.js
22
+
17
- - endpoints/
23
+ - routes/
18
24
 
19
25
  - index.js
20
26
 
21
- - views/
27
+ - views/
22
28
 
23
- - index.ejs
29
+ - index.ejs
24
30
 
25
31
  ```
26
32
 
@@ -66,45 +72,49 @@
66
72
 
67
73
  const express = require('express');
68
74
 
69
- const readdir = require('fs-readdir-recursive');
75
+ const router = require('./router');
70
76
 
71
77
  const app = express();
72
78
 
73
-
74
-
75
- // 再帰的にendpointsディレクトリ配下のjsを読み込んでappに登録していく
76
-
77
- readdir(`${__dirname}/endpoints`)
78
-
79
- .filter(it => /¥.js$/.test(it))
80
-
81
- .map(it => it.replace(/¥.js$/, ''))
82
-
83
- .forEach(name => {
84
-
85
- const endpoint = require(`./endpoints/${name}.js`);
86
-
87
- if (endpoint.get) {
88
-
89
- app.get(name, endpoint.get);
90
-
91
- }
92
-
93
- if (endpoint.post) {
79
+ const router(app);
94
-
95
- app.post(name, endpoint.post);
96
-
97
- }
98
-
99
- })
100
80
 
101
81
 
102
82
 
103
- // endpoints/index.js
83
+ // router/index.js
84
+
85
+ module.exports = app =>
86
+
87
+ readdir(`${__dirname}/endpoints`)
88
+
89
+ .filter(it => /¥.js$/.test(it))
90
+
91
+ .map(it => it.replace(/¥.js$/, ''))
92
+
93
+ .forEach(name => {
94
+
95
+ const endpoint = require(`./endpoints/${name}.js`);
96
+
97
+ if (endpoint.get) {
98
+
99
+ app.get(name, endpoint.get);
100
+
101
+ }
102
+
103
+ if (endpoint.post) {
104
+
105
+ app.post(name, endpoint.post);
106
+
107
+ }
108
+
109
+ })
110
+
111
+
112
+
113
+ // router/routes/index.js
104
114
 
105
115
  module.exports = {
106
116
 
107
- get: function (req, res) {
117
+ get: function (req, res, next) {
108
118
 
109
119
  res.render('/index', {title: 'Express'});
110
120
 

1

endpoints変数は使わないので削除

2018/01/04 00:38

投稿

miyabi-sun
miyabi-sun

スコア21158

test CHANGED
@@ -1,6 +1,8 @@
1
1
  そのindex.jsは少なくともViewではありません。
2
2
 
3
- Viewとは、「私に値を投げ込んだら、その値に応じたHTMLを自動生成するよ!」というものであり、リクエストを捌くものはエンドポイントやコントローラといったロールになります。
3
+ Viewとは、「私に値を投げ込んだら、その値に応じたHTMLを自動生成するよ!」というものであり、
4
+
5
+ リクエストを捌くものはエンドポイントやコントローラといったロールになります。
4
6
 
5
7
 
6
8
 
@@ -70,7 +72,9 @@
70
72
 
71
73
 
72
74
 
75
+ // 再帰的にendpointsディレクトリ配下のjsを読み込んでappに登録していく
76
+
73
- const endpoints = readdir(`${__dirname}/endpoints`)
77
+ readdir(`${__dirname}/endpoints`)
74
78
 
75
79
  .filter(it => /¥.js$/.test(it))
76
80