设计一个方法injectBeforeAsyncSend,能够实现如下功能:在发起异步请求之前打印出请求的类型、URL、method、body、timestamp 等信息。

异步请求逻辑注入
工作中我们需要对异步请求的请求信息打印日志,但是又不能耦合在业务代码中打印。请设计一个方法injectBeforeAsyncSend,能够实现如下功能:在发起异步请求之前打印出请求的类型、URL、method、body、timestamp 等信息。

/**

  • injectBeforeAsyncSend.js
  • @param {function(asynConfig)} beforeSend
    */
    const injectBeforeAsyncSend = function(beforeSend) {
    // 请在这里补充你的代码实现,在实现代码中请调用 beforeSend 方法进行日志打印
    };

injectBeforeAsyncSend((asynConfig) => {
console.log(asynConfig);
});

export default injectBeforeAsyncSend;

测试用例:
// 引入任意想使用的前端异步请求框架
import $ from 'jquery';
import injectBeforeAsyncSend from './injectBeforeAsyncSend';

// jquery 发起 get 请求
$.get('/user');
// 打印 {"asyncType":"ajax by XMLHttpRequest","method":"GET","url":"/user","body":null,"timestamp":1522143037821}

// jquery 发起带参数 post 请求
$.ajax('/user',
{
type: 'POST',
data: { username: 'jone' }
});
// 打印 {"asyncType":"ajax by XMLHttpRequest","method":"POST","url":"/user","body":"username=jone","timestamp":1522143037828}

// jquery 发起 jsonp 请求
$.ajax('https://www.alibaba.com/user.jsonp',
{
dataType: 'jsonp'
});
// 打印 {"asyncType":"jsonp by script","method":"get","url":"https://www.alibaba.com/user.jsonp?callback=jQuery331047025307012584316_1522143037811&_=1522143037812","timestamp":1522143037832}

// fetch 请求
fetch('/user');
// 打印 {"asyncType":"ajax by XMLHttpRequest","method":"GET","url":"/user","body":null,"timestamp":1522143037838}

posted @ 2018-09-06 22:28  阿明先森  阅读(312)  评论(0编辑  收藏  举报