The entrance

// package.json{...main: 'index.js'. }// index.js
module.exports = require('./lib/axios')
Copy the code

axios

var utils = require('./utils')
var bind = require('./helpers/bind')
var Axios = require('./core/Axios')
var mergeConfig = require('./core/mergeConfig')
var defaults = require('./defaults')
// Create an axios instance based on the method
var axios = createInstance(defaults)
axios.Axios = Axios
// The create method creates an Axios instance
axios.create = function create(instanceConfig){
  return createInstance(mergeConfig(axios.defaults,instanceConfig))
}
/ / extension Cancel/CancelToken/isCancel
axios.Cancel = require('./cancel/Cancel')
axios.CancelToken = require('./cancel/CancelToken')
axios.isCancel = require('./cancel/isCancel')
// Process concurrent requests
axios.all = function all(promises){
  return Promise.all(promises)
}
axios.spread = require('./helpers/spread')
axios.isAxiosError = require('./helpers/isAxiosError')
module.exports = axios
module.exports.default = axios
Copy the code

createInstance

function createInstance(defaultConfig){
  Instantiate the Axios object according to the configuration
  var context = new Axios(defaultConfig)
  // axios.prototype. request this points to an Axios instance
  var instance = bind(Axios.prototype.request,context)
  // Copy the Axios. Prototype property to the Axios instance with this pointing to
  utils.extend(instance,Axios.prototype,context)
  // Copy the Axios object's attributes to the request
  utils.extend(instance,context)
  return instance
}
Copy the code
bind
function bind(fn,thisArg){
  // The closure returns, binding this to
  return function wrap(){
    var args = new Array(arguments.length)
    for(var i = 0; i < args.length; i ++){
      args[i] = arguments[i]
    }
    return fn.apply(thisArg,args)
  }
}
Copy the code
util.extend
/ / forEach traversal
function extend(a,b,thisArg){
  forEach(b,function assignValue(val,key) {
    // Extend fuctionVal to bind this
    if(thisArg && typeof val === 'function'){
      a[key] = bind(val,thisArg)
    }else{
      a[key] = val
    }
  })
  return a
}
Copy the code

defaults

// Define the default data transfer format
var DEFAULT_CONTENT_TYPE = {'Content-Type':'application/x-www-form-urlencoded'}
// Default AXIOS configuration
var defaults = {
  transitional: {silentJSONParsing:true.Parse (response.body) error ignored
    forcedJSONParsing:true./ / when responseType! == json converts response to JSON
    clarifyTimeoutError:false.// Return ETIMEDOUT instead of ECONNABORTED when the request times out
  },
  adapter:getDefaultAdapter(), // Customize the request
  // Customize the data sent by the request before it reaches the server
  transformRequest: [function transformRequest(data,headers){
    normalizeHeaderName(headers,'Accept')
    normalizeHeaderName(headers,'Content-Type')
    // Processing for various types of requested data
    if(utils.isFormData(data) || utils.isArrayBuffer(data) || utils.isBuffer(data) || utils.isStream(data) || utils.isFile(data) || utils.isBlob(data)){
      return data
    }
    if(utils.isArrayBufferView(data)){
      return data.buffer
    }
    if(utils.isURLSearchParams(data)){
      setContentTypeIfUnset(headers,'application/x-www-form-urlencoded; charset=utf-8')
      return data.toString()
    }
    if(utils.isObject(data) || (header && headers['Content-Type'= = ='application/json')){
      SetContentTypeIfUnset(headers,'applicaion/json')
      return JSON.stringify(data)
    }
    return data
  }],
  //. Then /catch
  transformResponse: [function transformResponse(data){
    const transitional = this.transitional
    // Whether to ignore json.parse errors
    var slientJSONParsing = transitional && transitional.silentJSONParsing
    // Whether to force the conversion of res to JSON
    var forcedJSONParsing = transitional && transitional.forcedJSONParsing
    varstrictJSONParsing = ! silentJSONParsing &&this.responseType === 'json'
    if(strictJSONParsing || (forcedJSONParsing && utils.istring(data) && data.length)){
      try{
        return JSON.parse(data)
      }catch(e){
        if(strictJSONParsing){
          if(e.name === 'SyntaxError') {throw enhanceError(e,this.'E_JSON_PARSE')}throw e
        }
      }
    }
    return data
  }],
  timeout: 0.// Request supermarket time
  xsrfCookieName:'XSRF-TOKEN'.// The cookieName used to verify the XSRF request
  xsrfHeaderName:'X-XSRF-TOKEN'.// headerName used to verify XSRF request
  maxContentLength: -1.// The maximum character in the response body
  maxBodyLength: -1.// The maximum character of the request body
  validateStatus:function validateStatus(status){
    return status >= 200 && status < 300 // Verify the request success status
  }
}
defaults.headers = {
  common: {'Accept':'application/json,text/plain,*/*'}}/ / set the get/delete/head/post/put/patch default header content-type header
utils.forEach(['delete'.'get'.'head'].function forEachMethodNoData(method){
  defaults.headers[method] = {}
})
utils.forEach(['post'.'put'.'patch'].function forEachMethodWithData(method){
  defaults.headers[method] = utils.merge(DEFAULT_CONTENT_TYPE)
})
Copy the code
getDefaultAdapter
// Customize the request
function getDefaultAdapter(){
  var adapter
  // Check whether the current browser environment or node environment returns
  if(typeofXMLHttpRequest ! = ='undefined'){
    adapter = require('./adapter/xhr')}else if(typeofprocess ! = ='undefined' && Object.prototype.toString.call(process) === '[object process]'){
    adapter = require('./adapter/http')}return adapter
}
Copy the code
setContentTypeIfUnset
// Set the content-type of the header
function setContentTypeIfUnset(headers,value){
  if(! utils.isUndefined(headers) && utils.isUndefined(headers['Content-Type'])){
    headers['Content-Type'] = value
  }
}
Copy the code
normalizeHeaderName
// Clear the lower case setting of headers
function normalizeHeaderName(headers,normalizedName){
  utils.forEach(headers,function processHeader(value,name){
    if(name ! == normalizedName && name.toUpperCase() === normalizedName.toUpperCase()){ headers[normlizedName] = valuedelete headers[name]
    }
  })
}
Copy the code
merge
function merge(){
  var result = {}
  // Merge data
  function assignValue(val,key){
    if(isPlainObject(result[key]) && isPlainObject(val)){
      result[key] = merge(result[key],val)
    }else if(isPlainObject(val)){
      result[key] = merge({},val)
    }else if(isArray(val)){
      result[key] = val.slice()
    }else{
      result[key] = val
    }
  }
  // Iterate over the parameters
  for(var i = 0,l = arguments.length; i < l; i ++){ forEach(arguments[i],assignValue)
  }
}
Copy the code
enhanceError
// Generate an axios error message
function enhanceError(error,config,code,request,response){
  error.config = config
  if(code){
    error.code = code
  }
  error.request = request
  error.response = response
  error.isAxiosError = true
  error.toJSON = function toJSON(){
    return {
      message: this.message,
      name:this.name,
      description: this.description,
      number: this.number,
      fileName: this.fileName,
      lineNumber: this.lineNumber,
      columnNumber: this.columnNumber,
      stack:this.stack,
      config: this.config,
      code:this.code,
    }
  }
  return error
}
Copy the code