var request = require('request');
var qs=require( 'querystring' );
// 发起请求
var httpRequest = function (url,data=null,method="GET",headers={}){
  return new Promise((resolve, reject)=>{
    request({
      url: url+(method=="GET"?"?"+qs.stringify(data):""),
      method,
      json: true,
      headers:{
        "content-type":method=="GET"?"text/json":"application/x-www-form-urlencoded",
        ...headers
      },
      body:method=="POST"?qs.stringify(data):""
    }, function(error, response, body) {
      try {
        if (!error && response.statusCode == 200) {
          resolve(body)
        }else{
          reject(error)
        }
      } catch (error) {
        reject(error)
      }
        
    });
  })
}

module.exports = httpRequest;

  

posted on 2020-12-02 11:10  chenlw101  阅读(496)  评论(0编辑  收藏  举报