MirageJs: cannot use axios if I call api with passthrough

3k Views Asked by At

I have an app in react with a slice and a thunk. I use @reduxjs/toolkit and I created slice with "createSlice" api and thunk with "createAsyncThunk".

My thunk:

export const loginThunk = createAsyncThunk('login/local', async (loginData: LoginData) => {

    const {username, password} = loginData;
    
    const l = await axios.post(`${BASE_URL}_login/local`, {username, password}, {
        headers: {'Content-Type': 'application/json'}
    })
    return l.data;
})

In my app runs a mirage server with mock api and a "passthrough" at my true server.

When I dispatch "loginThunk" thunk, it runs the "loginThunk.pending" case in my reducer and stop.

Never it arrives to fulfilled or rejected.

If I dispatch "loginThunk" thunk, without mirage server running, it works.

If I dispatch "loginThunk" thunk, without mirage server running, but I use "fetch" instead axios, it works.

It seems is a problem between axios and mirageJs passthrough.

Any ideas??

Thank you so much

2

There are 2 best solutions below

2
On

Turns out the problem stems from the xhr adapter that was changed in axios 0.21.2. The handler request.onreadystatechange is not added to the request anymore (XMLHttpRequest seems to be redefined when you start your mirageJS server).

The solution is to create your own adapter - basically copy lib/adapters/xhr.js and make sure that the else branch of the if statement goes through - and use it in your axios config.

1
On

I fix the issue downgrading axios to 0.21.0 and works with miragejs: 0.1.41, 0.1.42.0, 0.1.43.0