Search code examples
javascriptreactjsreduxaxiosfrontend

Use axios and axios-mock-adapter for onSubmit event


I'm trying to use axios and axios-mock-adapter in one place to aggregate more mocks and then export the axios instance to use it wherever I want:

axios.js

import axios from 'axios';

let api = axios.create({
    baseURL: 'http://localhost:3500',
});

export default api

Login.js

import api from '../../../api/axios';
import MockAdapter from 'axios-mock-adapter';
let mock = new MockAdapter(api);
const LOGIN_URL = '/users';

const onSubmit = async data => {

 console.log(data);

 const user = data.loginEmail;
 const pwd = data.password

 const response = await mock.onPost(LOGIN_URL,
  JSON.stringify({ user, pwd }),
  {
    headers: { 'Content-Type': 'application/json' },
    withCredentials: true
  }
 );

console.log(response);
}

But I get this response:

{reply: ƒ, replyOnce: ƒ, passThrough: ƒ, abortRequest:ƒ,abortRequestOnce: ƒ, …}abortRequest: ƒ ()abortRequestOnce: ƒ()networkError: ƒ ()networkErrorOnce: ƒ ()passThrough: ƒ passThrough()reply: ƒ reply(code, response, headers)replyOnce: ƒ replyOnce(code, response, headers)timeout: ƒ ()timeoutOnce: ƒ ([[Prototype]]: Object

Can anyone help me? What did I miss?

It sends status 200 but it doesn't send any request to the server and it's like not connecting to the server


Solution

  • axios.js

    import axios from 'axios';
    
    let api = axios.create({
        baseURL: 'http://localhost:3500',
    });
    
    export default api
    

    The solution was about to change the Login.js

    // ** API
    import api from '@api';
    const LOGIN_URL = '/auth'
    
    

    And onSubmit Event

      // !! On Submit Event
      const onSubmit = async data => {
        const user = data.username;
        const pass = data.password;
    
        try {
          const response = await api.post(LOGIN_URL,
            JSON.stringify({ user, pass }),
            {
                headers: { 'Content-Type': 'application/json' },
                withCredentials: true
            }
          );
          .
          .
          .
       }