LoginSignup
1
0

More than 5 years have passed since last update.

シンプルなNodeサーバ

Last updated at Posted at 2018-09-11

POSTでjsonオブジェクトでパラメータなり何かを投げるとなにかJSONで投げ返してくるサーバを超簡単に作る

前回書いた https://qiita.com/makainuma/items/26e104138d864b2d8034 が更に簡略化できたので書いておく。

モジュールとしてこんなのを考える

exports.body = function(req, act) {
    console.log(req.body);
    let json_data = {"Name":"dummy1"};
    act(json_data);
}

req.bodyが送ってもらったPOSTで投げ込んだjsonオブジェクトのはずで、それをもとに何か処理を行って結果のオブジェクトをjson化したものがjson_dataであるとする。これを送り返させる。

これがmodules/mod1.jsだとして、それを呼び出す側は

const express = require('express')
const app = express();

app.use(express.urlencoded( {extended:true} ));
app.use(express.json());

app.use((req, res, next) => {
  res.header("content-type", "application/json;charset=utf-8");
  next();
});

const modules = [
  ['/mod1', require('./modules/mod1.js')],
  ['/mod2', require('./modules/mod2.js')],
  ['/mod3', require('./modules/mod3.js')],
];

modules.map((mod) => {
  app.post(mod[0], function(req, res) {
    mod[1].body(req, (ans) => {
      res.json(ans)
    });
  });
})

app.listen(3000, () => console.log('listening on port 3000!'))

のように記述する(mod1, mod2, mod3 と同じようにして複数機能を持たせたものとする)。
これをapp.jsだとして、npm install expressしておいてnode app.jsして起動。

投げる側は

curl -X POST http://localhost:3000/mod1 -H "Accept: application/json" -H "Content-type: application/json" -d '{ "param": "p0001" }

で投げる

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0