后端关闭时如何在React axios拦截器中模拟数据?

问题描述 投票:0回答:1

我想让全栈应用程序仅在前端工作时才工作。我已经准备好了模拟的 json 数据,我想将其传递给请求拦截器以使用这些模拟数据创建 Promise。

我尝试在拦截器中创建一个 if 语句,该语句查看 api 路径并将模拟数据注入其中。

import apiFriends from './mockedData/friends';

const zpiApi = axios.create({
  baseURL: API_BASE_URL,
  timeout: 10 * 1000,
});

zpiApi.interceptors.request.use((request) => {
  const token = localStorage.getItem('token');
  if (token) {
    request.headers.Authorization = `Bearer ${token}`;
  }
  console.log(request);

  if (request.url?.includes('/friends/search/')) {
    return Promise.resolve({
      ...request,
      headers: request.headers,
      data: apiFriends,
      status: 200,
      statusText: 'OK',
    });
  }

  return request;
});

export default zpiApi;

但是看起来它仍然与后端通信 - 它返回后端数据而不是模拟。

然后我尝试删除...请求,但这会删除整个配置,我收到这样的错误:

Cannot read properties of undefined (reading 'toUpperCase')
TypeError: Cannot read properties of undefined (reading 'toUpperCase')
    at dispatchXhrRequest (http://localhost:3000/static/js/bundle.js:153139:32)
    at new Promise (<anonymous>)
    at xhr (http://localhost:3000/static/js/bundle.js:153109:10)
    at Axios.dispatchRequest (http://localhost:3000/static/js/bundle.js:154301:10)
    at async FriendsService.getUsersBySearchPhrase (http://localhost:3000/static/js/bundle.js:18664:25)

这意味着根本没有配置(根据我在网上阅读的内容)。

所以我想做的是让特定的 api 调用使用模拟数据而不是后端,但现在我正在努力使其即使对于单个 api 调用也能工作。

从我在网上尝试找到的内容来看,只有关于玩笑中模拟数据的问题。

提前感谢大家。

reactjs axios request response interceptor
1个回答
0
投票

您可以使用名为

axios-mock-adapter
的库来模拟您的数据。这就像假装发出请求,但它不会访问服务器,而是使用您的模拟数据。

首先,您需要安装它。您可以通过在终端中运行

npm install axios-mock-adapter --save-dev
来完成此操作。

然后,在您的代码中,您可以像这样设置模拟:

import axios from 'axios';
import MockAdapter from 'axios-mock-adapter';

// This sets the mock adapter on the default instance
var mock = new MockAdapter(axios);

// Mock any GET request to /friends/search/
// arguments for reply are (status, data, headers)
mock.onGet('/friends/search/').reply(200, apiFriends);

现在,每当您向

/friends/search/
发出 GET 请求时,它都会返回您的
apiFriends
数据,而不是转到服务器。

© www.soinside.com 2019 - 2024. All rights reserved.