Home > Enterprise >  Axios post request is not working for a register form submission
Axios post request is not working for a register form submission

Time:12-13

I have a form built in react js and I am using an axios post request to register a user after form submission. I have tried to put a try catch block after the promise but i dont think i am getting passed the post request. I have imported axios and checked package json to make sure its downloaded. I have also implemented a catch block to catch errors but I am still getting

(TypeError: Cannot read properties of undefined (reading 'post'))

const handleSubmit = (e) => {
 e.preventDefault();
 axios.post('http://localhost:5000/api/users/register',{
  name: data.name,
  email:data.email,
  password: data.password
})
.then((res) => {
  console.log("server response:",res);
})
.catch((err) =>{
console.log("Server responded with error", err);
})

}

CodePudding user response:

It is indeed correct to use axios.post in that way but you are not handling a response or an error from the server. For these axios provides you with the .then() and .catch() methods, which handle the results/error for you.

Here's an example: (You can check the results of the post request in this example in the console tab or the network tab in the developer tools of your favorite browser).

const RegisterScreen = () => {
    const [ data, setData ] = useState({
        name: "",
        email: "",
        password: "",
        });

    const handleChange(e) => {
        setData({...data, [e.target.name]: e.target.value});
    }

    const handleSubmit = (e) => {
        e.preventDefault();
        axios.post("YOUR/URL:5000", {
            name: data.name,
            email: data.email,
            password: data.password
        })
        .then((res) => {
            console.log("Server response: ", res);
        })
        .catch((err) => {
            console.log("Server respondend with error: ", err);
        })
    } 
}

return (
     <>
        <YourForm />
     </>
     );
}

CodePudding user response:

You may have to specify the content type while sending a POST request.

const handleSubmit = (e) => {
 e.preventDefault();
 axios.post('http://localhost:5000/api/users/register',{
  name: data.name,
  email:data.email,
  password: data.password
}, {
    headers: {
      'Content-Type': 'application/json'  } 
  })
.then((res) => {
  console.log("server response:",res);
})
.catch((err) =>{
console.log("Server responded with error", err);
})
}
  • Related