发布于 4年前

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

自己记录 不喜勿喷

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
  })
})
©2020 edoou.com   京ICP备16001874号-3