最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to work with path parameters in Axios Mock adapter - Stack Overflow

programmeradmin1浏览0评论

I am using axios mock adapter to mock the data for my react front-end. Currently I am working with param and it was working. But i need to support it to following url

.../invoice/1

This is my code

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;
};

I am using axios mock adapter to mock the data for my react front-end. Currently I am working with param and it was working. But i need to support it to following url

.../invoice/1

This is my code

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;
};
Share Improve this question edited Aug 31, 2020 at 14:52 NearHuscarl 81.4k22 gold badges318 silver badges280 bronze badges asked Mar 7, 2019 at 8:00 Pubudu JayasankaPubudu Jayasanka 1,4624 gold badges22 silver badges36 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 7

Since this is one of the top results when searching for "axios mock adaptor with token in path", I'll just point out that the GitHub README for axios mock adaptor has the solution. https://github.com/ctimmerm/axios-mock-adapter

You can pass a Regex to .onGet, so for your case -

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

That should pick up your calls to /invoice/${id}

For anyone who also wants to get the js object from dynamic query string of the url

mock.onGet(/api\/test\/?.*/).reply((config) => {
  console.log(config.url, parseQueryString(config.url));
  return [202, []];
});

function parseQueryString(url: string) {
  const queryString = url.replace(/.*\?/, '');

  if (queryString === url || !queryString) {
    return null;
  }

  const urlParams = new URLSearchParams(queryString);
  const result = {};

  urlParams.forEach((val, key) => {
    if (result.hasOwnProperty(key)) {
      result[key] = [result[key], val];
    } else {
      result[key] = val;
    }
  });

  return result;
}

Result

axios.get("api/test");
// api/test
// null

axios.get("api/test?foo=1&bar=two");
// api/test?foo=1&bar=two
// {foo: "1", bar: "two"}

axios.get("api/test?foo=FOO&bar=two&baz=100");
// api/test?foo=FOO&bar=two&baz=100
// {foo: "FOO", bar: "two", baz: "100"}

axios.get("api/test?foo=FOO&bar=two&foo=loo");
// api/test?foo=FOO&bar=two&foo=loo
// {foo: ["FOO", "loo"], bar: "two"}

Live Demo

Following @NearHuscarl answer; and fixing

Do not access Object.prototype method hasOwnProperty from target object. eslintno-prototype-builtins

you could:

function parseQueryString(url: string) {
  const queryString = url.replace(/.*\?/, '');

  if (queryString === url || !queryString) {
    return null;
  }

  const urlParams = new URLSearchParams(queryString);
  const result = {};

  urlParams.forEach((val, key) => {
    if (Object.prototype.hasOwnProperty.call(result, key)) {
      result[key] = [result[key], val];
    } else {
      result[key] = val;
    }
  });

  return result;
}

that is, replacing result.hasOwnProperty(key) with Object.prototype.hasOwnProperty.call

发布评论

评论列表(0)

  1. 暂无评论