0

I have created the api with route api/login, I have client in server folder so it can be the url without http (I have proxy for that). The problem is when I submit the request. I have 500 error in browser(from catch(error) ). Here is my action creater:

export const loginUser = (email,password) => {
  return function(dispatch) {
    // const token = 'my secret token', I dont know where to put it
   axios.post(
       'api/login', {email: email, password: password}
   ).then((response) => dispatch({type: LOGIN_USER, payload:response}))
  .catch((error) => {
  console.log("axios error:",error);
  });
 }
}

In submit function in React I have email and password as a state, so I pass it into action. I am not sure what I have to put in axios, I suppose I need to add by secret token from jwt?

I really appreciate any advises. Thank you in advance.

Michał
  • 101
  • 10

1 Answers1

0

in the normal application when you’ve logged in successfully then gives you access token... 500 error means probably you have problem to backand(in my opinion).

i show you my examples login helper function

function signin(email, password) {
    const user = axios({
        method: 'post',
        url: 'url',
        data: {
            email,
            password,
        },
        responseType: 'json',
    });
    return user;
}

this is action creator

export const login = (email, password) => async (dispatch, getState, api) => {
    dispatch(request());
    try {
        const res = await api.signin(email, password);
        localStorage.setItem('token', res.data.token);
        return dispatch(success(res.data.user));
    } catch (error) {
        dispatch(failure(error.response.data.message));
    }
};

and also i have one more function which have auth header.
each request to back checks expired or not my token let see

function getProfile(token) {
    const user = axios({
        method: 'get',
        url: 'url',
        headers: {
            Authorization: `Bearer ${token}`,
        },
        responseType: 'json',
    });

    return user;
}

and in front i have error handler function which checks if returns 401 error redirecting to login page