Help us understand the problem. What is going on with this article?

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

More than 3 years have passed since last update.

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"}
}
penta515
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
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  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
ユーザーは見つかりませんでした