588.md 2.7 KB
Newer Older
Lab机器人's avatar
readme  
Lab机器人 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
# Axios

> 原文:[https://docs.gitlab.com/ee/development/fe_guide/axios.html](https://docs.gitlab.com/ee/development/fe_guide/axios.html)

*   [CSRF token](#csrf-token)
*   [Usage](#usage)
*   [Mock Axios response in tests](#mock-axios-response-in-tests)
    *   [Example](#example)
    *   [Mock poll requests in tests with Axios](#mock-poll-requests-in-tests-with-axios)

# Axios[](#axios "Permalink")

我们使用[Axios](https://github.com/axios/axios)在 Vue 应用程序和大多数新代码中与服务器进行通信.

为了确保设置了所有默认值,您不应*直接使用 Axios* ,而应从`axios_utils`导入 Axios.

## CSRF token[](#csrf-token "Permalink")

我们所有的请求都需要 CSRF 令牌. 为了确保设置此令牌,我们将导入[Axios](https://github.com/axios/axios) ,设置令牌并导出`axios` .

应该使用此导出模块,而不是直接使用 Axios 以确保已设置令牌.

## Usage[](#usage "Permalink")

```
 import axios from './lib/utils/axios_utils';

  axios.get(url)
    .then((response) => {
      // `data` is the response that was provided by the server
      const data = response.data;

      // `headers` the headers that the server responded with
      // All header names are lower cased
      const paginationData = response.headers;
    })
    .catch(() => {
      //handle the error
    }); 
```

## Mock Axios response in tests[](#mock-axios-response-in-tests "Permalink")

为了帮助我们模拟响应,我们使用[axios-mock-adapter](https://github.com/ctimmerm/axios-mock-adapter) .

[`spyOn()`](https://jasmine.github.io/api/edge/global.html#spyOn)优势:

*   无需创建响应对象
*   不允许通话(我们要避免)
*   简单的 API 来测试错误情况
*   提供`replyOnce()`以允许不同的响应

我们还决定不使用[Axios 拦截器,](https://github.com/axios/axios#interceptors)因为它们不适合模拟.

### Example[](#example "Permalink")

```
 import axios from '~/lib/utils/axios_utils';
  import MockAdapter from 'axios-mock-adapter';

  let mock;
  beforeEach(() => {
    // This sets the mock adapter on the default instance
    mock = new MockAdapter(axios);
    // Mock any GET request to /users
    // arguments for reply are (status, data, headers)
    mock.onGet('/users').reply(200, {
      users: [
        { id: 1, name: 'John Smith' }
      ]
    });
  });

  afterEach(() => {
    mock.restore();
  }); 
```

### Mock poll requests in tests with Axios[](#mock-poll-requests-in-tests-with-axios "Permalink")

因为轮询功能需要一个标头对象,所以我们需要始终包含一个对象作为第三个参数:

```
 mock.onGet('/users').reply(200, { foo: 'bar' }, {}); 
```