LoginSignup
0
0

Express で簡単な WebAPI を作成

Last updated at Posted at 2020-01-18

必要なライブラリーのインストール

sudo npm install -g express
sudo npm install -g cfenv

サーバープログラム

フォルダー構造

$ tree
.
├── app.js
└── routes
    └── index.js
app.js
//-------------------------------------------------------------------------
//	app.js
//
//					May/24/2023
//-------------------------------------------------------------------------
const express = require('express')
const routes = require('./routes')
const cfenv = require('cfenv')

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

app.use(express.static(__dirname + '/public'))

var appEnv = cfenv.getAppEnv()

app.post('/post_test',routes.post_test)

app.listen(appEnv.port, '0.0.0.0', function() {
  console.log("server starting on " + appEnv.url)
})

//-------------------------------------------------------------------------
routes/index.js
// -----------------------------------------------------------------------
/*
	routes/index.js

						Jan/18/2020
*/
// -----------------------------------------------------------------------
exports.post_test = function(req,res)
{
	var aa = 0
	var bb = 0

	if (req.body.aa) {
		aa = parseInt(req.body.aa,10)
		}

	if (req.body.bb) {
		bb = parseInt(req.body.bb,10)
		}

	var dict_aa = {}
	dict_aa["aa"] = aa
	dict_aa["bb"] = bb
	dict_aa["sum"] = aa + bb
	dict_aa["diff"] = aa - bb

	var str_out = JSON.stringify(dict_aa)

	res.send(str_out)
}

// -----------------------------------------------------------------------

サーバーの起動

$ export NODE_PATH=/usr/lib/node_modules
$ node app.js 
server starting on http://localhost:3000

curl のテストスクリプト

go_test.sh
#
URL=http://localhost:3000/post_test
#
curl -X POST -d aa="12" -d bb="45" $URL
#
echo
#
curl -X POST -H "Content-Type: application/json" \
	-d '{"aa":"32", "bb":"41"}'  $URL
#
echo
#
curl -X POST -H "Content-Type: application/json" \
	-d@in01.json $URL
#
echo
#
in01.json
{"aa":"52", "bb":"84"}

実行結果

$ ./go_test.sh 
{"aa":12,"bb":45,"sum":57,"diff":-33}
{"aa":32,"bb":41,"sum":73,"diff":-9}
{"aa":52,"bb":84,"sum":136,"diff":-32}

HTTPie のテストスクリプト

go_http.sh
URL=http://localhost:3000/post_test
#
http POST $URL aa="12" bb="45"
#
echo
#
echo '{"aa":"32", "bb":"41"}' | http POST $URL
#
echo
#
http POST $URL < in01.json
#
echo
#

確認したバージョン

$ node --version
v20.2.0

$ npm info express version
4.18.2
0
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
0
0