axios returning no server response despite Satus 200

Viewed 49

So I'm trying to create a login form with formik and axios

const LOGIN_URL = 'http://localhost:8081/api/authenticate';

//

const formik = useFormik({
  initialValues: {
    username: '',
    password: '',
  },
  validationSchema: Yup.object({
    password: Yup.string()//.oneOf([Yup.ref('confirmPassword')], 'Mot de passe différent!')
      .required('Champ obligatoire'),
    username: Yup.string().required('Champ obligatoire'),
  }),
});
const { setAuth } = useContext(AuthContext);
const userRef = useRef();
const errRef = useRef();

const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const [errMsg, setErrMsg] = useState('');
const [success, setSuccess] = useState(false);
useEffect(() => {
  userRef.current.focus();
}, [])

useEffect(() => {
  setErrMsg('');
}, [username, password])

const handleSubmit = async (e) => {
  e.preventDefault();

  try {
    const response = await axios.post(LOGIN_URL,
      formik.values,
      {
        headers: {
          'Content-Type': 'application/json',
          'Authorization': 'Basic Y2xpZW50OnNlY3JldA==',
          'access-control-allow-origin': 'http://localhost:*/',
        },
        withCredentials: true
      }
    );

    console.log(JSON.stringify(response?.data));
    //console.log(JSON.stringify(response));
    const accessToken = response?.data?.accessToken;
    const roles = response.data.roles;
    console.log(response.status);
    console.log(response.data);
    setAuth({username,password,roles,accessToken});
    setUsername('');
    setPassword('');
    setSuccess(true);


  } catch (err) {
    if (!err.response) {
      setErrMsg('No Server Response');
      console.log(err.response.status);

    } else if (err.response.status === 400) {
      setErrMsg('Missing Username or Password');

    } else if (err.response.status === 401) {
      setErrMsg('Unauthorized');

    } else if (err.response.status === 404) {
      setErrMsg('NOT FOUND');

    } else {
      setErrMsg('Login Failed');

    }
    errRef.current.focus();
    console.log(err);
  }
}

the problem is it gets the access token it returns Status 200 but after that it just says no Server response and when you console log the error it says undefined??

Console Log

same code works fine on an other react page (landing page)

0 Answers
Related