is there a way to intercept an Axios request and return a custom response instead?

Viewed 717

So I am trying to intercept my axios call in other return a custom response. I checked the axios.interceptors but it seems they are not used the way I want to use it.

const axios = require('axios')

const url = 'https://jsonplaceholder.typicode.com/posts/';
const request = axios({
      method: 'GET',
      url,
    });

// some middleware to intercept the request and return a custom response

request.then(customResponse => console.log(customResponse))
1 Answers

Take a look to axios-mock-adapter.

Example (from the documentation)


var axios = require("axios");
var MockAdapter = require("axios-mock-adapter");

// This sets the mock adapter on the default instance
var 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" }],
});

axios.get("/users").then(function (response) {
  console.log(response.data);
});
Related