使用 axios-mock-adapter 时出现 404 错误

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

我相信我无法配置 axios-mock-adapter。我的文件是:

axiosConfig.ts


const axiosInstance = axios.create({
baseURL: 'http://localhost:3000', // Localhost
headers: {
'Content-Type': 'application/json',
},
});

export default axiosInstance;

模拟Axios.ts

import MockAdapter from 'axios-mock-adapter';
import axiosInstance from './axiosConfig';

const mockAxios = new MockAdapter(axiosInstance, { delayResponse: 200 });

// Mock responses
const projects = [
  { id: 1, name: 'Project 1' },
  { id: 2, name: 'Project 2' },
  { id: 3, name: 'Project 3' },
  { id: 4, name: 'Project 4' },
  { id: 5, name: 'Project 5' },
];

mockAxios.onGet('/projects/fetchAll').reply(200, { data: projects });

export default mockAxios;

projectsApi.ts

import axios from 'axios';

const fetchAllProjects = async () => {
    console.log('Fetching all projects');
    const res = await axios.get('/projects/fetchAll');
    console.log(res);
    return res;
}

export { fetchAllProjects };

我尝试像

const response = await fetchAllProjects();         console.log(response);
那样调用它,但是这个调用在projectsApi.ts文件中收到404错误,因为它打印Fetching all items but no res。

我不知道还能做什么,但我尝试使用mockAxios.onAny() 调用。这里的其他帖子没有解决我的问题。

javascript axios http-status-code-404 axios-mock-adapter
1个回答
0
投票
  • 您没有使用配置的

    axiosInstance

  • 您应该在mock之后调用API函数。

例如

axiosConfig.ts

import axios from 'axios';

const axiosInstance = axios.create({
    baseURL: 'http://localhost:3000', // Localhost
    headers: {
        'Content-Type': 'application/json',
    },
});

export default axiosInstance;

projectsApi.ts

import axiosInstance from './axiosConfig';

const fetchAllProjects = async () => {
    console.log('Fetching all projects');
    const res = await axiosInstance.get('/projects/fetchAll');
    console.log(res.data);
    return res;
};

export { fetchAllProjects };

main.ts

import './mockAxios';
import { fetchAllProjects } from './projectsApi';

function main() {
    fetchAllProjects();
}

main();

执行结果:

$ npx ts-node ./main.ts
Fetching all projects
{
  data: [
    { id: 1, name: 'Project 1' },
    { id: 2, name: 'Project 2' },
    { id: 3, name: 'Project 3' },
    { id: 4, name: 'Project 4' },
    { id: 5, name: 'Project 5' }
  ]
}
© www.soinside.com 2019 - 2024. All rights reserved.