node axios不强制使用环境变量
emer 发布于 2021-8-17 18:15 1579 次阅读
const axios = require('axios') const { httpsOverHttp, httpOverHttp } = require('tunnel-agent') const TUNNEL_OPTIONS = { proxy: { port: } } axios.interceptors.request.use(function (config) { config.proxy = false // 强制禁用环境变量中的代理配置 config.httpAgent = httpOverHttp(TUNNEL_OPTIONS) config.httpsAgent = httpsOverHttp(TUNNEL_OPTIONS) return config })
这种方式使得 proxy 与 agent 配置参数无法被业务更改,但是的确是一种可行的方法。 $ node --require ./one.jsconst axios = require('axios')// const { httpsOverHttp, httpOverHttp } = require('tunnel-agent')// const TUNNEL_OPTIONS = { proxy: { port: } }axios.interceptors.request.use(function (config) {config.proxy = {protocol: 'http',host: '127.0.0.1',port: 10,// auth: {// username: 'mikeymike',// password: 'rapunz3l'// }}// 强制禁用环境变量中的代理配置// config.httpAgent = httpOverHttp(TUNNEL_OPTIONS)// config.httpsAgent = httpsOverHttp(TUNNEL_OPTIONS)return config})axios.get('http://lininn.cn').then(res=>{console.log(res)})