使用NodeJS的request模块进行同步处理

由于在2020年2月之后,Request模块已被官方弃用,因此请参考以下网站获取最新的方法。

使用Node.js的五种使用Aysnc/Await进行HTTP请求的方法。

尽管不被推荐使用,但由于仍有人使用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模块可以更加简便地实现,但该模块也已被弃用。

在Node.js中,使用同期请求模块返回request模块的返回值(非回调方式)。建议在Node.js中使用then-request来进行HTTP通信,而不推荐使用sync-request。

const request = require('sync-request');
const res = request('GET', 'https://httpbin.org/json', {});
console.log(res.body.toString());