This repository was archived by the owner on Apr 8, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample.js
More file actions
82 lines (73 loc) · 3.06 KB
/
Copy pathexample.js
File metadata and controls
82 lines (73 loc) · 3.06 KB
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
const path = require('path');
const express = require('express') // 導入(require 相當於 "import") express 模組 (架設網站伺服器)
const app = express(); // 初始化 express
const fs = require('fs'); // require fs 模組 (檔案管理)
const bodyParser = require('body-parser'); // require body-parser 模組 (取得 POST Body)
const jsonParser = bodyParser.json(); // create application/json parser
const firestore = require('./dht11firebase.js').Firestore; // require Firestore (自製外部 class)
const serviceAccount = require("./serviceAccountKey.json");
const myFirestore = new firestore(serviceAccount); // 初始化 Firestore 物件
const port = process.env.PORT || 80; // 設定 Heroku port 本機做測試時 port 改為 80
appGetByFile("/", "./html/index.html");
appGetByFile("/main", "./html/main.js", "javascript");
function appGetByFile(name, path, type = "html") {
app.get(name, (req, res) => {
const data = fs.readFileSync(path, 'utf8');
let myHead = {
"Content-Type": `text/${type}; charset=UTF-8`,
"Content-Length": Buffer.byteLength(data, 'utf8')
}
res.writeHead(200, myHead);
res.write(data);
res.end();
});
}
app.post('/data/checkIdPasswd', jsonParser, async (req, res) => {
console.log("Check ID Passwd:");
console.log(req.body);
res.writeHead(200, {"Content-Type": "text/json"});
await myFirestore.checkIdPasswd(req.body)
.then(success => {
console.log("send:");
console.log(success);
res.write(JSON.stringify(success));
res.end();
})
.catch(fail => {
console.log(fail);
res.end();
});
});
app.post('/data/setDHT11Data', jsonParser, (req, res) => {
console.log("Set DHT11 Data:");
console.log(req.body);
res.writeHead(200, {"Content-Type": "text/json"});
myFirestore.setDHT11Data(req.body)
.then(success => {
console.log("send:");
console.log(success);
res.write(JSON.stringify(success));
res.end();
})
.catch(fail => {
console.log(fail);
res.end();
});
});
app.post('/data/getDHT11Data', jsonParser, async(req, res) => {
console.log("Get DHT11 Data:");
console.log(req.body);
res.writeHead(200, {"Content-Type": "text/json"});
await myFirestore.getDHT11Data(req.body)
.then(success => {
console.log("send:");
console.log(success);
res.write(JSON.stringify(success));
res.end();
})
.catch(fail => {
console.log(fail);
res.end();
});
});
app.listen(port);