Skip to content
Advertisement

Why is the request not being delivered and refreshing on request to axios

Send email and password to axios as a post request The server responds with a bearer token in the header. We are implementing the login function by storing the token in local storage. However, there are times when you run the code, and there are times when it doesn’t. When it does not run, the page is refreshed when the button is clicked, and the console window of the Chrome developer tool is also opened. As a result of checking with the console log, the function is executed, but it seems that refreshing occurs when a request is made to axios. Can I see what’s wrong?

https://codesandbox.io/s/cranky-sun-l36oz

const login = () => {
  setLoading(true);
  axios({
     url: 'api url',
     method: 'POST',
     data: {
       email: email,
       password: password,
     },
     headers: {
       'Content-Type': 'application/json',
     },
   })
     .then((response) => {
       token = response.headers.authorization;
       console.log(token);
       localStorage.setItem('authorization', token);
       alert('success');
       setLoading(false);
     })
     .catch((error) => {
       console.log(error.status);
     });
 };

Advertisement

Answer

Based on what I understand from your post, you want to prevent the page from refreshing when you send Axios request. (Luckily, I can understand your Google-translated English a little more because I am from South Korea.)

You can use event.preventDefault() in the login handler to stop the page from refreshing. I test the code below in your code sandbox and the page is not refreshed anymore.

const login = (e) => {
  e.preventDefault()
  setLoading(true);
  axios({
     url: 'api url',
     method: 'POST',
     data: {
       email: email,
       password: password,
     },
     headers: {
       'Content-Type': 'application/json',
     },
   })
     .then((response) => {
       token = response.headers.authorization;
       console.log(token);
       localStorage.setItem('authorization', token);
       alert('success');
       setLoading(false);
     })
     .catch((error) => {
       console.log(error.status);
     });
 };
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement