Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationEventAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
74
Help us understand the problem. What are the problem?

More than 1 year has passed since last update.

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

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しないでそのまま試せますね。

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
74
Help us understand the problem. What are the problem?