美文网首页
Nodejs request 请求库默认值以及全局请求拦截设置

Nodejs request 请求库默认值以及全局请求拦截设置

作者: lihao_李浩 | 来源:发表于2019-05-14 16:14 被阅读0次

    自己记录 不喜勿喷

    import request from 'request'
    
    var j = request.jar();
    var localStorageCookie = localStorage.getItem('cookie')
    
    
    if(localStorageCookie){
      localStorageCookie = JSON.parse(localStorageCookie)
      console.log('历史cookie:',localStorageCookie)
      localStorageCookie.cookies.map(it=>{
        j._jar.setCookieSync(it.key+'='+it.value,'https://***.***.cn'+it.path)
      })
    }
    
    function parseBody(body) {
      var out;
      if (typeof body == 'string') {
        try {
          out = JSON.parse(body)
        } catch (err) {
          out = body;
        }
      } else {
        return body;
      }
    
      return out;
    }
    
    Vue.prototype.$request = request.defaults({
      jar: j,
      'proxy': 'http://127.0.0.1:8808',//代理
      timeout: 1000 * 15,
      baseUrl: 'https://**.***.cn',
      rejectUnauthorized: false,//忽略证书验证
      headers: {
        "User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.79 Safari/537.36"
      }
    }, function (target, callback) {
      if (/^http/.test(target.url)) {
        delete target.baseUrl;
      }
      console.log('请求--------->>>>', target.url)
      return request(target, function (err, res, body) {
        if (callback) {
          body = parseBody(body)
          callback.call(this, err, res, body)
        }
      }).on('end', () => {
        
        var cookie = j._jar.toJSON()
        
        localStorage.setItem('cookie', JSON.stringify(cookie))
      }).on('error', () => {
        // debugger
      })
    })
    

    相关文章

      网友评论

          本文标题:Nodejs request 请求库默认值以及全局请求拦截设置

          本文链接:https://www.haomeiwen.com/subject/edxeaqtx.html