gpt4 book ai didi

javascript - 如何在 Axios Mock 适配器中使用路径参数

转载 作者:行者123 更新时间:2023-12-01 16:10:52 25 4
gpt4 key购买 nike

我正在使用 axios 模拟适配器来模拟我的 react 前端的数据。目前我正在使用 param 并且它正在工作。但我需要支持它来关注 url

.../发票/1

这是我的代码

let mock;
if (process.env.REACT_APP_MOCK_ENABLED === 'true') {
console.log('Simulation mode is enabled ');
mock = new MockAdapter(axios);

mock
.onGet(apiUrl + '/invoice').reply(
(config) => {
return [200, getMockInvoice(config.params)];
})
.onGet(apiUrl + '/invoices').reply(
(config) => {
return [200, getMockInvoices(config.params)];
});
}
export const getInvoice = async (id) => {
console.log(id);
try {
const invoiceResponse = await axios.get(apiUrl + `/invoice/${id}`);
return invoiceResponse.data;
} catch (e) {
console.log(e);
}
};
export const getMockInvoice = (params) => {
let invoices = mockData.invoices;
let selectedInvoice = {} ;
for(let i in invoices){
let invoice = invoices[i];
if(invoice.invoiceNo === params.invoiceNo){
selectedInvoice = invoice;
}
}
return selectedInvoice;
};

最佳答案

由于这是搜索“在路径中带有 token 的 axios 模拟适配器”时的最佳结果之一,我只想指出 axios 模拟适配器的 GitHub README 有解决方案。 https://github.com/ctimmerm/axios-mock-adapter

您可以将正则表达式传递给 .onGet ,所以对于你的情况 -

const pathRegex = new Regexp(`${apiUrl}\/invoice\/*`);
mock
.onGet(pathRegex).reply
...etc.etc.

那应该会接听您对 /invoice/${id} 的电话

关于javascript - 如何在 Axios Mock 适配器中使用路径参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55038758/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com