LoginSignup
113
94

More than 5 years have passed since last update.

node.js + expressでPOSTを受け取る & POSTパラメータをJSONで取得する

Last updated at Posted at 2016-08-28

バージョン

  • node.js: v6.2.2
  • express: 4.14.0
  • body-parser: 1.15.2

expressでPOSTを受け取る

app.js側を用意する

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

const app = express();

app.listen(3000);
console.log('Server is online.');

app.post('/', function(req, res) {
    res.send('POST is sended.');
})

curlでたたく

$ curl -X POST http://localhost:3000

POSTパラメータをJSONで取得する

app.js側を用意する

POSTパラメータをJSONで取得するにはbody-parserを使う。

app.js
const express = require('express');
const bodyParser = require('body-parser');

const app = express();

// urlencodedとjsonは別々に初期化する
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');
})

curlで叩く

HTTPHeaderでapplication/jsonを受け付けるように記述。
-dオプションでパラメータを追加。

$ curl -X POST http://localhost:3000 -H "Accept: application/json" -H "Content-type: application/json" -d '{ "name" : "tanaka" }'

出力結果

Server is online.
{ name: 'tanaka' }
tanaka

参考

113
94
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
113
94