Error reported while sending data using Axios in REACTJS

Getting could not insert data alert when button submitted… Why is it executing the catch part ?

import './App.css';
import { useState} from "react";
import Axios from 'axios';                                

function App() {

  const [name, setName] = useState("");
  const [age, setAge] = useState(0);

  const addUser = () => {
    Axios.post("http://localhost:3001/adduser", {         
      name: name, 
      age: age,
    }).then(() => {                                         
        alert("data inserted successfully..");
    }).catch(() => {
        alert("could not insert data..");
    });           
  };

  return (
    <div className="App">
      <div className="inputs">
        <input 
          type="text" 
          placeholder="Your name here..." 
          onChange={(event) => {
            setName(event.target.value);
            }}
        />
        <input 
          type="number" 
          placeholder="Your age here..."
          onChange={(event)=> {
            setAge(event.target.value);
          }}
        />
        <button onClick={ addUser }>Add User</button>      
      </div>      
    </div>
  );
}

export default App;

It is running the catch block because something is throwing the error. To you have any info in the network tab of your dev tools? Why not catch the error:

    }).catch(err => {
        alert("could not insert data..", err);
    });  

Dev Tools gives me this

Hey I just found out the reason, :innocent: I was was using POST in the front-side with Axios and in the back-end express part i used a GET which was causing the error. Now it’s all working. :innocent:

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.