Axios源码研究学习系列---xhr请求模块大概分析

 改变是人生的定律,专注于过去和现在的人,必将错过未来

首先文件结构,插件标准模式,严格模式,用ES6语法promise返回,所以就是常见的axios.get(url).then(res=>{})形式

'use strict';

var utils = require('./../utils');
var settle = require('./../core/settle');
var buildURL = require('./../helpers/buildURL');
var parseHeaders = require('./../helpers/parseHeaders');
var isURLSameOrigin = require('./../helpers/isURLSameOrigin');
var createError = require('../core/createError');

module.exports = function xhrAdapter(config) {
  return new Promise(function dispatchXhrRequest(resolve, reject) {
     //启动请求
     request.open(config.method.toUpperCase(), buildURL(config.url, config.params,         config.paramsSerializer), true);
     ...
     settle(resolve, reject, response) //给promise返回resolve和reject两种状态
     ...
     // 发送请求
     request.send(requestData);  
  }
}

由于用到promise,那么resolve和reject状态就显得非常重要,我们先看下settle函数 settle(resolve, reject, response),位于settle.js中

'use strict';

var createError = require('./createError');

/**
 * Resolve or reject a Promise based on response status.
 *
 * @param {Function} resolve A function that resolves the promise.
 * @param {Function} reject A function that rejects the promise.
 * @param {object} response The response.
 */
module.exports = function settle(resolve, reject, response) {
  var validateStatus = response.config.validateStatus;
  if (!validateStatus || validateStatus(response.status)) { //验证响应状态是否通过
    resolve(response);
  } else {
    reject(createError(
      'Request failed with status code ' + response.status,
      response.config,
      null,
      response.request,
      response
    ));
  }
};

settle函数里面对resolve和reject进行了条件判断,在reject时候,有调用createError函数,进行输出。我们使用axios请求接口,不通,控制台会输出相关报错信息就是该函数封装的

我们先看输出resolve的条件,使用了response.config.validateStatus,它到底是什么,它就是defaults.js中一个验证状态码是否是[200,300)区间,表示请求通过

var defaults = {
  ...
  //验证状态码是否处于200-300之间,就是请求通过状态
  validateStatus: function validateStatus(status) {
    return status >= 200 && status < 300;
  }
};

但是为何会response.config.validateStatus这样写,那么分析发现,这是xhr.js文件传参config的配置

module.exports = function xhrAdapter(config) {
  return new Promise(function dispatchXhrRequest(resolve, reject) {
     var response = {
        data: responseData,
        status: request.status,
        statusText: request.statusText,
        headers: responseHeaders,
        config: config, //传进来的参数
        request: request
      };

      settle(resolve, reject, response); 
  }
}

那么我们再简单看下cofig.validateStatus中间做了些什么,还是defaults.js文件

function getDefaultAdapter() {
  var adapter;
  // Only Node.JS has a process variable that is of [[Class]] process
  if (typeof process !== 'undefined' && Object.prototype.toString.call(process) === '[object process]') {
    // For node use HTTP adapter
    adapter = require('./adapters/http');
  } else if (typeof XMLHttpR

你可能感兴趣的:(Vuejs学习系列,ES6学习系列,vue.js,javascript,前端,node.js,es6)