LoginSignup
3
6

More than 3 years have passed since last update.

Node.jsでrequestモジュールを使ってHTTPリクエストを実行する

Last updated at Posted at 2020-06-13

Node.jsでHTTPリクエストを使う

前回の記事のとおり、Raspberry piでNode.js環境を整えました。

requestモジュールを準備する

このページを参考にしました。

requestモジュールをインストールする。

pi@raspberrypi:~ $ npm install request

バージョンを確認します。

pi@raspberrypi:~ $ npm view request version
2.88.2

requestモジュールを利用してPOSTメソッドを実行する

HTTPリクエストのPOSTメソッドを試してみます。

コードは、この記事を参考にしました。

上記記事のソースを利用して、URLはこのサーバを利用しています。

post.jsというファイル名で下記ソースコードを用意しました。

var webclient = require("request");

webclient.post({
  url: "https://httpbin.org/post",
  headers: {
    "content-type": "application/json"
  },
  body: JSON.stringify({foo: "bar"})
}, function (error, response, body){
  console.log(body);
});

さて、実行してみます。

正常に結果が返ってきました。
originのところはIPアドレスをマスクしています。

pi@raspberrypi:~/myapp $ node post.js
{
  "args": {},
  "data": "{\"foo\":\"bar\"}",
  "files": {},
  "form": {},
  "headers": {
    "Content-Length": "13",
    "Content-Type": "application/json",
    "Host": "httpbin.org",
    "X-Amzn-Trace-Id": "Root=1-5ee4dfca-46fbf47877b927fa5750c822"
  },
  "json": {
    "foo": "bar"
  },
  "origin": "**.**.**.**",
  "url": "https://httpbin.org/post"
}

まとめ

今回は、requestモジュールをインストールして、
HTTPリクエストのPOSTメソッドを試してみました。

次は、IFTTTのWebhookを試してみようと思います。

3
6
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
3
6