Home > Back-end >  Can log in user on Postman, but not on browser
Can log in user on Postman, but not on browser

Time:12-15

If I can log in a user to Postman, then that means its my front end code that has a bug. Right?

CastError: Cast to string failed for value "{ email: '[email protected]', password: '123456' }" (type Object) at path "email" for model "User"

It seems that path "email" is both taking in the email and password into one input. Is the problem in my front end or back end? I am using react-final-form

Reducer:

export const userLoginReducer = (state = {}, action) => {
  switch (action.type) {
    case USER_LOGIN_REQUEST:
      return { loading: true };
    case USER_LOGIN_SUCCESS:
      return { loading: false, userInfo: action.payload };
    case USER_LOGIN_FAIL:
      return { loading: false, error: action.payload };
    case USER_LOGOUT:
      return {};
    default:
      return state;
  }
};

Action:

export const login = (email, password) => async (dispatch) => {
  try {
    dispatch({
      type: USER_LOGIN_REQUEST,
    });

    const config = {
      headers: {
        "Content-Type": "application/json",
      },
    };

    const { data } = await axios.post(
      "/api/users/login",
      { email, password },
      config
    );

    dispatch({
      type: USER_LOGIN_SUCCESS,
      payload: data,
    });

    localStorage.setItem("userInfo", JSON.stringify(data));
  } catch (error) {
    dispatch({
      type: USER_LOGIN_FAIL,
      payload:
        error.response && error.response.data.message
          ? error.response.data.message
          : error.message,
    });
    toast.error("Invalid Credentials");
  }
};

Store

import {
  userLoginReducer,
} from "./reducers/userReducers";

const reducer = combineReducers({
  userLogin: userLoginReducer,
});

const userInfoFromStorage = localStorage.getItem("userInfo")
  ? JSON.parse(localStorage.getItem("userInfo"))
  : null;

const initialState = { userLogin: { userInfo: userInfoFromStorage } };

CodePudding user response:

Based on the error, I suspect the error is due to your request body potentially not being a string.

I'd try updating your post to be the following:

    const { data } = await axios.post(
      "/api/users/login",
      { JSON.stringify(email), JSON.stringify(password) },
      config
    );

Which will ensure your request is passed to the server as a string

  • Related