LoginSignup
145

More than 5 years have passed since last update.

Node.jsのrequestモジュールを使ってHTTPSでPOSTリクエストを行う

Posted at

requestモジュール

requestモジュールは HTTP/HTTPS 通信を行うためのクライアント。

request - https://github.com/request/request

全体のソースコード

//requestをrequire
var request = require('request');

//ヘッダーを定義
var headers = {
  'Content-Type':'application/json'
}

//オプションを定義
var options = {
  url: 'https://hoge.com/api/v2/fuga',
  method: 'POST',
  headers: headers,
  json: true,
  form: {"hoge":"fuga"}
}

//リクエスト送信
request(options, function (error, response, body) {
  //コールバックで色々な処理
})

解説

requestモジュール読み込み。

var request = require('request');

ヘッダーを定義する。
今回の例ではjsonをPOSTするため、Content-Type に json を指定した。

var headers = {
  'Content-Type':'application/json'
}

オプションを定義する。
レスポンスでjsonが帰ってくる場合、オプションにjson:trueを指定することでjsonエンコードの必要が無くなる。
( JSON.parseの必要が無くなる )

var options = {
  url: 'https://hoge.com/api/v2/fuga',
  method: 'POST',
  headers: headers,
  json: true,
  form: {"hoge":"fuga"}
}

おまけ

POSTの際にBasic認証が必要な場合は、オプションに auth を付け加えれば良い。

var options = {
  url: 'https://hoge.com/api/v2/fuga',
  method: 'POST',
  headers: headers,
  auth: {
    user: "username",
    password: "password"
  },
  json: true,
  form: {"hoge":"fuga"}
}

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
145