Skip to content

Instantly share code, notes, and snippets.

@katsube
Last active January 26, 2019 19:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save katsube/e9605c1fc14f78c5af3b27de91690655 to your computer and use it in GitHub Desktop.
Save katsube/e9605c1fc14f78c5af3b27de91690655 to your computer and use it in GitHub Desktop.
/**
* JSONデータ保管用の簡易Webサーバ
*/
//--------------------------------------
// モジュール読み込み
//--------------------------------------
const port = 3001;
const app = require('express')();
const http = require('http').Server(app);
const bodyParser = require('body-parser');
//--------------------------------------
// JSONデータ格納用
//--------------------------------------
let DB = [];
let DB_ID = 1;
//--------------------------------------
// ミドルウェア
//--------------------------------------
// 全API共通
app.use( (req, res, next) => {
res.set('Access-Control-Allow-Origin', '*');
next();
});
// POST取得
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
//--------------------------------------
// Webサーバ
//--------------------------------------
// Webサーバを起動
http.listen(port, ()=>{
console.log(`listening on *:${port}`);
});
/**
* データを取得
*/
app.get('/get', (req, res)=>{
res.send(JSON.stringify({status:"OK", data:DB}));
});
app.get('/get/:id', (req, res)=>{
let id = Number(req.params.id);
let buff = DB.filter( i => i.id === id);
res.send(JSON.stringify({status:"OK", data:buff}));
});
/**
* データをt追加
*/
app.post('/set', (req, res)=>{
try{
let data = JSON.parse(req.body.data);
data["id"] = DB_ID++;
DB.push(data);
res.send(JSON.stringify({status:"OK"}));
}
catch(e) {
res.send(JSON.stringify({status:false, message:"Can not parse JSON"}));
}
});
/**
* データを削除
*/
app.get('/remove/:id', (req, res)=>{
let id = Number(req.params.id);
let buff = DB.filter( i => i.id !== id);
DB = buff;
res.send(JSON.stringify({status:"OK"}));
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment