76
80

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Node.jsでJSONデータをHTTP POSTするメモ

Last updated at Posted at 2016-10-01

Node.jsでHTTP GETしてJSONパースするメモを発見したのでPOSTも書こうかと思ったらrequestモジュールを使う例ばかりで素のサンプルが少なかったのでメモです。

Node.jsはv6.6.0です。

試す内容

http://requestb.in/wm8697wm に対して

以下のJSONデータをPOSTしてみます。

{
    "name": "n0bisuke",
    "comment": "nemui"
}
  • curlの例

curlだとたぶんこんな感じ

curl -d '{"name":"n0bisuke","comment":"nemui"}' -H 'Content-Type: application/json' http://requestb.in/wm8697wm

こういうときにrequestb.inがすごく便利ですよね。

コード

app.js
'use strict'

const http = require('http');
const HOST = `requestb.in`;
const PATH = `/wm8697wm`;

let postData = {
    "name": "n0bisuke",
    "comment": "nemui"
};

let postDataStr = JSON.stringify(postData);
let options = {
    host: HOST,
    port: 80,
    path: PATH,
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
        'Content-Length': Buffer.byteLength(postDataStr)
    }
};

let req = http.request(options, (res) => {
  console.log('STATUS: ' + res.statusCode);
  console.log('HEADERS: ' + JSON.stringify(res.headers));
  res.setEncoding('utf8');
  res.on('data', (chunk) => {
    console.log('BODY: ' + chunk);
  });
});
req.on('error', (e) => {
  console.log('problem with request: ' + e.message);
});
req.write(postDataStr);
req.end();

実行

$node app.js

STATUS: 200
HEADERS: {"date":"Sat, 01 Oct 2016 15:39:33 GMT","content-type":"text/html; charset=utf-8","transfer-encoding":"chunked","connection":"close","set-cookie":["__cfduid=d9e2d353c3ca9f35720ad33b07bc569791475336373; expires=Sun, 01-Oct-17 15:39:33 GMT; path=/; domain=.requestb.in; HttpOnly"],"sponsored-by":"https://www.runscope.com","via":"1.1 vegur","server":"cloudflare-nginx","cf-ray":"2eb1020e83f62df7-NRT"}
BODY: ok

requestbinはリクエスト成功するとBODYがOKとでるので成功してることがわかります。
requestbinのサイト側を見に行くと、更にリクエストの詳細を見れるのでデバッグに使えます。

httpモジュールだけでいけるのでnpm iしないでそのまま試せますね。

76
80
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
76
80

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?