Node request异步获取数据

2018-05-16  本文已影响0人  好了伤疤忘了痛_伪全栈

使用node Request包异步获取数据示例

 const request = require('request');
 class FetchData {
    
    FetchData( url, params = {}, method = false, headers = false, json = true ){
        let _json   = json || false;
        let _method = method ? 'POST' : 'GET';
        let _headers = headers ? headers : {"content-type": "application/json"};

        return new Promise( ( resolve, reject ) => {
            request({
                url: url,
                method: _method,
                json: _json,
                headers: _headers,
                body: JSON.stringify( params )
            }, function( error, response, body ){
                if (!error && response.statusCode == 200) {
                    resolve( body );
                }else{
                    reject( error );
                }
            });
        })
    }
 }
 module.exports = new FetchData;

结束语

对你有帮助或喜欢的话,欢迎关注、打赏,收藏,谢谢!

上一篇下一篇

猜你喜欢

热点阅读