api/app.js

96 lines
2.6 KiB
JavaScript
Raw Permalink Normal View History

2021-04-24 13:21:23 +00:00
// 背景執行 forever start -w -a -l api.log app.js
// 監聽檔案變化 nodemon app.js
// npm start
// npm run dev
// Debug nodemon --inspect=192.168.168.15:9229 app.js
const dateFormat = require('dateformat');
require('dotenv').config()
const http = require('http');
const https = require('https');
const fs = require('fs');
const express = require('express');
const app = express();
//讀取憑證及金鑰
const prikey = fs.readFileSync('privkey.pem', 'utf8');
const cert = fs.readFileSync('cert.pem', 'utf8');
const cafile = fs.readFileSync('chain.pem', 'utf-8');
//建立憑證及金鑰
const credentials = {
key: prikey,
cert: cert,
ca: cafile
};
const CPBLClass = require('./CPBLClass');
const { decode } = require('querystring');
const CPBL = new CPBLClass();
const port = process.env.PORT || 3000;
const server = https.createServer(credentials, async function (req, res) {
// const server = http.createServer(async function (req, res) {
// console.log(`rawBody: ${req.rawBody}`);
// res.writeHead(200);
if (req.method === 'POST') {
// console.log(`body: ${JSON.stringify(req.body)}`);
let Request = req.url.replace("/", "");
let Response = "";
let data = '';
req.on('data', chunk => {
data += chunk;
});
req.on('end', async () => {
switch (req.headers["content-type"]) {
case "application/x-www-form-urlencoded": {
data = decode(data);
// data = []
// let strs = str.split("&");
// for (let i = 0; i < strs.length; i++) {
// data[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
// }
break;
}
case "application/json": {
data = JSON.parse(data);
break;
}
default:
break;
}
switch (Request) {
case "CPBL":
Response = await CPBL.GetCPBL(data);
break;
case "CPBLList":
Response = await CPBL.GetCPBLList(data);
break;
default:
break;
}
res.writeHead(200);
res.write(Response);
return res.end();
});
// } else if (req.method === 'GET' && req.url === path) {
// let Response = await CPBL.GetCPBL();
// res.writeHead(200);
// res.write(Response);
// return res.end();
} else {
res.statusCode = 404;
res.setHeader('Content-Type', 'text/html; charset=utf-8');
return res.end('Not found');
}
});
server.listen(port, function () {
let datetime = dateFormat(new Date(), "yyyy-mm-dd HH:MM:ss");
console.log(`${datetime} listening on ${port}`);
console.log(`${datetime} [api已準備就緒]`);
});