-
Notifications
You must be signed in to change notification settings - Fork 43
/
Copy pathindex.js
executable file
·107 lines (92 loc) · 2.48 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
import express from "express";
const app = express();
const port = 8000;
// application/json リクエストボディの受け取り
app.use(express.json()); // application/json
app.get("/", function (req, res) {
res.send("Express!");
});
app.get("/json", function (req, res) {
res.json({ key: "value", json: "データ" });
});
app.get("/redirect", function (req, res) {
res.redirect(301, "/redirected");
});
app.get("/redirected", function (req, res) {
res.send("redirected!");
});
app.get("/404", (req, res) => {
res.status(404).send("そんなページないよ!");
});
app.get("/500", (req, res) => {
res.status(500).send({ error: "何かがおかしいのです..." });
});
app.get("/header", (req, res) => {
res.setHeader("X-red", "panda");
res.send("X-red ヘッダ付きです!");
});
app.get("/nopower", (req, res) => {
// デフォルト付与されるヘッダを削除する
res.removeHeader("X-Powered-By");
res.send("X-Powered-By ヘッダ消しました");
});
app.get("/cleaning", (req, res) => {
var filename = "cleaning.jpg";
var options = {
root: ".",
dotfiles: "deny",
};
res.sendFile(filename, options, (err) => {
if (err) {
res.send(err);
} else {
console.log("Sent: ", filename);
}
});
});
app.get("/query", (req, res) => {
console.log(req.query);
res.send(`クエリ: ${JSON.stringify(req.query)}`);
});
function handler1(req, res, next) {
console.log("ハンドラー1 (応答返さない)");
// req.startTime = Date.now();
req.startTime = new Date();
next();
}
function handler2(req, res, next) {
console.log("ハンドラー2 (まだ応答返さない)");
next();
}
app.get(
"/starttime",
[handler1, handler2],
(req, res, next) => {
console.log("クライアントへの応答は次のハンドラーで返します ...");
next();
},
(req, res) => {
res.send(`${req.startTime} に API アクセスされました!`);
}
);
app.get(
"/api/path",
[handler1, handler2],
function (req, res, next) {
console.log("クライアントへの応答は次のハンドラーで返します ...");
next();
},
function (req, res) {
res.send("API の応答です!");
}
);
// curl http://localhost:8000/profile -X POST
// -H "Content-Type: application/json" -d '{"name":"名前", "age":20}'
//
app.post("/profile", function (req, res, next) {
console.log(req.body);
res.json(req.body);
});
app.listen(port, () => {
console.log(`サンプルアプリを起動します`);
});