Quantcast
Channel: Node.jsタグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 8932

【Node.js】request promise 使い方

$
0
0

自分が使っていて分からなかったことを備忘録として書き残しておきます。

使い方

request-promise自体は以下のgithubで公開されている。
https://github.com/request/request-promise


インストール

npm経由でinstall

npm install --save request
npm install --save request-promise

javascriptで使うには、requireでrequest promiseを読みこむ。

constrp=require('request-promise')

オプションを作る

  • url

GETしたい挿し先のURLを記入する。queryを入れた状態でもいい。
例 ) https://sample.jp/sample/?query1=AAA

  • method

GET

constoption={url:'https://test.jp/test/',method:'GET',qs:{query1:'AAA',query2:'BBB',}}

POST (HTML Form)

constoption={url:'https://test.jp/test/',method:'POST',form:{query1:'AAA',query2:'BBB'}}

各クエリがなければ省いてもらってかまいません。

  • headers
constoption={...headers:{// curlの-Hに該当します。'content-type':'appilication/json'}}

optionのparamは名前が違うとダメなのでheadersをheaderにしたりしてないかを確認してください。

request

先ほど作ったオプションを元にHTTP通信を行います。

rp(option).then((res)=>{returnJSON.parse(res)}).catch((err)=>{console.log(err)returnnull});

メソッドチェーンで値を取得してからの動きを続けて記述していくことができます。
スクレイピングできたり、APIから〜みたいな派生が無限に生まれるので、今後も使っていきたいですね。

最終形態

sample.js
"use strict"constrp=require('request-promise')/**
 * @constructor
 * @param {Json} query query: data
 * @return {Json} query 結果
 */constrPModule=function(query){this.option={url:'',// 取得先method:'GET',qs=query}}rpModule.prototype.getData=function(){rp(this.option).then((res)=>{returnJSON.parse(res)}.catch((err)=>{console.log(err)}}module.exports=rpModule

こんな感じにするとどこからでも呼び出せるAPIアクセスモジュールみたいな利用ができると思います。

読み込み側

index.js
constrpModule=require('./sample.js')// 読み込みたいパスを指定する...// queryの作成...constrpM=newrpModule(query)letdata=rpM.getData()console.log(data)

読み込み側はこんな感じでしょうか。

以上で、request promiseの備忘録を終了します。


Viewing all articles
Browse latest Browse all 8932

Trending Articles