毎回、忘れるので備忘録
初期設定
$ npm init
$ npm i express
サーバー側のプログラム
app.js
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
app.listen(3000);
console.log('Server is online.');
app.post('/', function(req, res) {
// リクエストボディを出力
console.log(req.body);
// パラメータ名、nameを出力
console.log(req.body.name);
res.send('POST request to the homepage');
})
サーバーを立ち上げて
node app.js
ターミナルウィンドウをもう1つ開いて
以下curlで叩く
$ curl -X POST http://localhost:3000 -H "Accept: application/json" -H "Content-type: application/json" -d '{ "name" : "tatsuya" }'
出力結果 ( node app.js の方)
{ name: 'tatsuya' }
tatsuya
以上です。