adapter
getDefaultAdapter
function getDefaultAdapter(){
var adapter
// Request in the window browser environment
if(typeofXMLHttpRequest ! = ='undefined'){
adapter = require('./adapters/xhr')}else if(typeofprocess ! = ='undefined' && Object.prototype.toString.call(process) === '[object process]') {// Request in node environment
adapter = require('./adapters/http')}return adapter
}
Copy the code
http
var isHttps = /https:? /
function httpAdapter(config){
return new Promise(function(resolve,reject){
var resolve = function(val) {resolvePromise(val)}
var reject = function(val){rejectPromise(val)}
var data = config.data
var headers = config.headers
// Set up the user agent
if('User-Agent' in headers || 'user-agent' in headers){
// User-agent does not exist to clear
if(! headers['User-Agent'] && !headers['user-agent']) {delete headers['User-Agent']
delete headers['user-agent']}}else{
/ / set the User Agents
headers['User-Agent'] = 'axios/'+pkg.versiob
}
// Set the data to be transferred
if(data && ! utils.isStream(data)){if(Buffer.isBuffer(data)){}else if(utils.isArrayBuffer(data)){
data = Buffer.from(new Uint8Array(data))
}else if(utils.isString(data)){
data = Buffer.from(data,'utf-8')}else{
return reject(createError('Data after transformation must be a string,an ArrayBuffer,a Buffer,or a Stream',config,))
}
headers['Content-Length'] = data.length
}
// User authentication
var auth = undefined
if(config.auth){
var username = config.auth.username || ' '
var password = config.auth.password || ' '
auth = username + ':' + password
}
// Get the request interface
var fullPath = buildFullPath(config.baseUrl,config.url)
var parsed = url.parse(fullPath)
var protocol = parsed.protocol || 'http:'
// User authentication information
if(! auth && parsed.auth){var urlAuth = parsed.auth.split(':')
var urlUsername = urlAuth[0] | |' '
var urlPassword = urlAuth[1] | |' '
auth = urlUsername + ':' + urlPassword
}
if(auth){
delete headers.Authorization
}
// Verify whether the user agent is obtained through HTTPS links
var isHttpsRequest = isHttps.test(protocol)
var agent = isHttpsRequest ? config.httpsAgent : config.httpAgent
// Request configuration
var options = {
path: buildURL(parsed.path,config.params,config.paramsSerializer).replace(/ ^ \? /.' '),
method: config.method.toUpperCase(),
headers,
agent,
agents: {http:config.httpAgent,https:config.httpsAgent},
auth
}
// Set the request address
if(config.socketPath){
options.socketPath = config.socketPath
}else{
options.hostname = parsed.hostname
options.port = parsed.port
}
var proxy = config.proxy
if(! proxy && proxy ! = =false) {var proxyEnv = protocol.slice(0, -1) + '_proxy'
var proxyUrl = process.env[proxyEnv] || process.env[proxyEnv.toUpperCase()]
if(proxyUrl){
var parsedProxyUrl = url.parse(proxyUrl)
var noProxyEnv = process.env.no_proxy|| process.env.NO_PROXY
var shouldProxy = true
// Check whether the default proxy is not configured or the current interface does not match the default proxy
if(noProxyEnv){
var noProxy = noProxyEnv.split(', ').map((s) = >s.trim()) shouldProxy = ! noProxy.some((proxyElement) = >{
if(! proxyElement){return false
}
if(proxyElement=== The '*') {return true
}
if(proxyElement[0= = ='. ' && parsed.hostname.substr(parsed.hostname.length - proxyElement)){
return true
}
return parsed.hostname === proxyElement
})
}
if(shouldProxy){
// Set the interface proxy according to the configuration
proxy = {
host:parsedProxyUrl.hostname,
prot:parsedProxyUrl.port,
protocol:parsedProxyUrl.protocol
}
if(parsedProxyUrl.auth){
var proxyUrlAuth = parsedProxyUrl.auth.split(':')
proxy.auth = {
username:proxyUrlAuth[0].password:proxyUrlAuth[1]}}}}}// Set the proxy
if(proxy){
options.headers.host = parsed.hostname + (parsed.port ? ':' + parsed.port : ' ')
setProxy(options,proxy,protocol+'/ /'+parsed.hostname+(parsed.port ? ':'+parsed.port : ' ')+options.path)
}
var transport
// Determine the request method
var isHttpsProxy = isHttpsRequest && (proxy ? isHttps.test(proxy.protocol) : true)
if(config.transport){
transport = config.transport
}else if(config.maxRedirects === 0){
transport = isHttpsProxy ? https : http
}else{
if(config.maxdirects){
options.maxdirects = config.maxdirects
}
transport = isHttpsProxy ? httpsFollow : httpFollow
}
if(config.maxBodyLength > -1){
options.maxBodyLength = config.maxBodyLength
}
// Create the request
var req = transport.request(options,(res) = > {
if(req.aborted) return
var stream = res
var lastRequest = res.req || req
// If the connection is not requested and the compressed content is returned, decompress
if(res.statusCode ! = =204&& lastRequest.method ! = ='HEAD'&& config.decompress ! = =false) {switch(res.headers['content-encoding']) {case 'gzip':
case 'compress':
case 'deflate':
stream = stream.pipe(zlib.createUnzip())
delete res.headers['content-encoding']
break}}var response = {
status:res.statusCode,
statusText: res.statusMessage,
headers:res.headers,
config,
request:lastRequest
}
// Direct return for stream data
if(config.responseType === 'stream'){
response.data = stream
settle(resolve,reject,response)
}else{
// Other types of data are read
var responseBuffer = []
var totalResponseBytes = 0
// Stream data processing
stream.on('data'.(chunk) = > {
responseBuffer.push(chunk)
totalResponseBytes += chunk.length
if(config.maxConentLength > -1 && totalResponseBytes > config.maxContentLength){
stream.destroy()
reject(createError('maxContentLength size of ' + config.maxContentLength + 'exceeded',config,null,lastRequest))
}
})
stream.on('error'.(err) = > {
if(req.aborted) return
reject(enhanceError(err,config,null,lastRequest))
})
stream.on('end'.() = > {
var responseData = Buffer.concat(responseBuffer)
if(config.responseType ! = ='arraybuffer'){
responseData = responseData.toString(cofig.responseEncoding)
if(! config.responseEncoding || config.responseEncoding ==='utf8'){
responseData = utils.stripBOM(responseData)
}
}
response.data = responseData
settle(resolve,reject,response)
})
}
})
// Request error
req.on('error'.(err) = > {
if(req.aborted && err.code ! = ='ERR_FR_TOO_MANY_REDIRECTS') return
reject(enhanceError(err,config,null,req))
})
if(config.timeout){
var timeout = parseInt(config.timeout,10)
if(isNAN(timeout)){
reject(createError('error trying to parse `config.timeout` to int',config,'ERR_PARSE_TIMEOUT',req))
return
}
// The request timed out
req.setTimeout(timeout,() = > {
req.abort()
reject(createError('timeout of '+timeout+'ms exceded',config,config.transitional && config.transitional.clarifyTimeoutError ? 'ETIMEDOUT': 'ECONNABORTED',req))
})
}
if(config.cancelToken){
config.cancelToken.promise.then((cancel) = > {
if(req.aborted) return
req.abort()
reject(cancel)
})
}
// Initiate a request
if(utils.isStream(data)){
data.on('error'.(err) = > {
reject(enhanceError(err,config,null,req))
}).pipe(req)
}else{
req.end(data)
}
})
}
Copy the code
setProxy
function setProxy(options,proxy,location){
// Set the proxy
options.hostname = proxy.host
options.host = proxy.host
options.port = proxy.port
options.path = proxy.location
if(proxy.auth){
var base64 = Buffer.from(proxy.auth.username + ':'+proxy.auth.password,'utf-8').toString('base64')
options.headers['Proxy-Authorization'] = 'Basic' + base64
}
// Redirect proxy Settings
options.beforeRedirect = (redirection) = > {
redirection.headers.host = redirection.host
setProxy(redirection,proxy,redirection.href)
}
}
Copy the code