LoginSignup
5
5

More than 3 years have passed since last update.

NodeJSのrequestモジュールで同期処理する

Last updated at Posted at 2021-04-20

requestモジュールは、2020年2月の時点で非推奨になってしまったので、
最新の方法は以下のサイトを見てください。

Node.jsでAysnc/Awaitを使ってHTTPリクエストを行う5つの方法

非推奨とはいえ、requestは未だに使用されているので以下に書いておきます。

request= require('request');
const rqt = (url) => {
    return new Promise((resolve, reject)=> {
        request(url, (error, response, body)=> {
            resolve(body);
        });
    });
}

(async () => { 
    const body = await rqt('https://httpbin.org/json')
    console.log(body);
})();

sync-requestモジュールだともっと簡単にできるが、こちらも非推奨になっている。

同期処理でrequestモジュールの戻り値を返す(Node.js)(非コールバック)
Node.jsのHTTP通信はsync-request非推奨でthen-requestを推奨

const request = require('sync-request');
const res = request('GET', 'https://httpbin.org/json', {});
console.log(res.body.toString());
5
5
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
5
5