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
xhr
function xhrAdapter(config){
return new Promise(function(resolve,reject){
var requestData = config.data
var requestHeaders = config.headers
var responseType = config.responseType
// fromData requests data and the request data type is set by the browser
if(utils.isFormData(requestData)){
delete requestHeaders['Content-Type']}var request = new XMLHttpRequest()
// User authentication
if(config.auth){
var username = config.auth.username || ' '
var password = config.auth.password ? unescape(encodeURIComponent(config.auth.password)) : ' '
requestHeaders.Authorization = 'Basic' + bota(username + ':' + password)
}
var fullPath = buildFullPath(config.baseURL,config.url)
// Initiate a request
request.open(config.method.toUpperCase(),buldURL(fullPath,config.params,config.paramsSerializer),true)
// Set request timeout
request.timeout = config.timeout
function onloadend(){
if(! request){return
}
// Format the response header
const responseHeaders = 'getAllResponseHeaders' in request ? parseHeaders(request.getAllResponseHeaders()) : null
// Get the response
varresponseData = ! responseType || responseType==='text' || responseType === 'json' ? response.responseText : response.response
var response = {data:responseData,status:request.status,statusText:request.statusText,headers:responseHeaders,config,request}
// Check whether the response status matches
settle(resolve,reject,response)
request = null
}
if('onloadend' in request){
// Determine the end of the request
request.onloadend = onloadend
}else{
request.onreadystatechange = function(){
// The request status is not finished
if(! request || ! request.readyState ! = =4) {return
}
if(request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') = = =0)) {// file:// protocol request status is 0 even if successful
return
}
// The request was successfully processed
setTimeout(onloadend)
}
}
request.onabort = function(){
if(! request)return
// Request interrupt/error
reject(createError('Request aborted',config,'ECONNABORTED',request))
request = null
}
// Request error
request.onerror = function(){
reject(createError('Network Error',config,null,request))
request = null
}
// The request timed out
request.ontimeout = function(){
var timeoutErrorMessage = 'timeout of'+config.timeout+ 'ms exceeded'
if(config.timeoutErrorMessage){
timeoutErrorMessage = config.timeoutErrorMessage
}
reject(createError(timeoutErrorMessage,config,config.transitional && config.transitional.clarifyTimeoutError ? 'ETIMEDOUT' : 'ECONNABORTED',request))
request = null
}
/ / set xsrfcookie
if(utils.isStandardBrowserEnv()){
var xsrfValue = (config.withCredentials || isURLSameOrigin(fullPath)) && config.xsrfCookieName ? cookies.read(config.xsrfCookieName) :null
if(xsrfValue){
requestHeaders[config.xsrfCookieName] = xsrfValue
}
}
if('setRequestHeader' in request){
utils.forEach(requestHeaders,function(val,key){
// Delete the Content-type request header if the request transfer data is null
if(typeof requestData === 'undefined' && key.toLowerCase() === 'Content-Type') {delete requestHeaders[key]
}else{
// Set the request header
request.setRequestHeader(key,val)
}
})
}
// Request transfer cookie carry
if(! utils.isUndefined(config.withCredentials)){ request.withCredentials = !! config.withCredentials }// Response data format
if(responseType && responseType ! = ='json'){
request.responseType = config.responseType
}
// Add the download progress
if(typeof config.onDownloadProgress === 'function'){
request.addEventListener('progress',config.onDownloadProgress)
}
// Add the upload progress
if(typeof config.onUploadProgress === 'function' && request.upload){
request.upload.addEventListener('progress',config.onUploadProgress)
}
// Determine the interrupt request
if(config.cancelToken){
config.cancelToken.promise.then(function(cancel){
if(! request){return
}
request.abort()
reject(cancel)
request = null})}if(! requestData){ requestData =null
}
// Send request data
request.send(requestData)
})
}
Copy the code
buildFullPath
// Get the request path
function buildFullPath(baseURL,requestedURL){
if(baseURL && ! isAbsoluteURL(requestedURL)){return combineURLs(baseURL,requestedURL)
}
return requestedURL
}
Copy the code
isAbsoluteURL
// Check whether the root path contains the protocol
function isAbsoluteURL(url){
return /^([a-z][a-z\d\+\-\.]*:)? \/\//i.test(url)
}
Copy the code
combineURLs
// Merge request paths
function combineURLs(baseUrl,relativeUrl){
return relativeUrl ? baseUrl.replace(/ / / + $/.' ') +'/'+relativeUrl.replace(/ ^ \ / + /.' ') : baseUrl
Copy the code
parseHeaders
var ignoreDuplicateOf = ['age'.'authorization'.'content-length'.'content-type'.'etag'.'expires'.'from'.'host'.'if-modified-since'.'if-unmodified-since'.'last-modified'.'location'.'max-forwards'.'proxy-authorization'.'referer'.'retry-after'.'user-agent']
function parseHeaders(headers){
var parsed = {}
var key,val,i;
if(! headers){return parsed}
utils.forEach(headers.split('\n'),function(line){
i = line.indexOf(':')
/ / get the key/val
key = utils.trim(line.substr(0,i)).toLowerCase()
val = utils.trim(line.substr(i+1))
if(key){
//ignoreDuplicateOf takes only once
if(parsed[key] && ignoreDuplicatedOf.indexOf(key) >= 0) {return
}
/ / get the header
if(key === 'set-cookie'){
parsed[key] = (parsed[key] ? parsed[key] : []).concat([val])
}else{
parsed[key] = parsed[key] ? parsed[key] +', '+val:val
}
}
})
return parsed
}
Copy the code
settle
function settle(resolve,reject,response){
var validateStatus = response.config.validateStatus
// Check whether the status code of the response matches and return
if(! response.status|| ! validateStatus || validateStatus(response.status)){ resolve(response) }else{
reject(createError('Request Failed with status code:' + response.status,response.config,null,response.request,response))
}
}
Copy the code
createError
function createError(message,config,code,request,response){
var error = new Error(message)
return enhanceError(error,config,code,request,response)
}
Copy the code
cookies
// Public cookie library
module.exports = {
utils.isStandardBrowserEnv() ? (function standardBrowserEnv(){
return {
/ / write cookies
write:(name,value,expires,path,domain,secure) = > {
var cookie = []
cookie.push(name +'='+encodeURIComponent(value))
if(utils.isNumber(expires)){
cookie.push('expires='+new Date(expires).toGMTString())
}
if(utils.isString(path)){
cookie.push('path='+path)
}
if(utils.isString(domain)){
cookie.push('domain='+domain)
}
if(secure == true){
cookie.push('secure')}document.cookie = cookie.join('; ')},/ / read cookies
read:(name) = > {
var match = document.cookie.match(new RegExp(` (^ |; \\s*)(${name}) = (/ ^; *) `))
return match ? decodeURIComponent(match[3) :null
},
// Remove cookies/set timeout
remove:(name) = >{
this.write(name,' '.Date.now() - 86400000}}})() : (function nonStandardBrowserEnv(){
return {
write:() = > {},
read:() = > null.remove:() = >} {}}}) ()Copy the code
isStandardBrowserEnv
function isStandardBrowserEnv(){
// Verify that the current environment is a browser environment and not an RN environment
if(typeofnavigator ! = ='undefined' && (navigator.product === 'ReactNative' || navigator.product === 'NativeScript' || navigator.product === 'NS')) {return false
}
return typeof window! = ='undefined' && typeof document! = ='undefined'
}
Copy the code