title: Error when Posting Data with Axios - MERN Stack
body: <p>I'm trying to test validation for my model, specifically if a <code>name</code> variable is of a certain length. I have a front-end setup at <code>http://localhost:3000/</code> with <code>React</code> + <code>axios</code> and a backend setup with <code>express</code> + <code>node</code>.</p>
  <p>I've set a proxy in my frontend's <code>package,json</code> file to include <code>&quot;proxy&quot;: &quot;http://localhost:3001&quot;</code> and made sure that my backend includes CORS policy enabled:</p>
  <pre><code>const app = express()
  const cors = require('cors')
  app.use(cors())
  </code></pre>
  <p>However, when I post the data, although the validation output does display in the backend's console, the frontend appears as a blank screen and errors are displayed in the frontend's console. My goal is to have an error message appear in the front end.</p>
  <p>Front end error:
  <a href="https://i.stack.imgur.com/hElmN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hElmN.png" alt="enter image description here" /></a></p>
  <p>Backend output (fine):
  <a href="https://i.stack.imgur.com/rLJ99.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rLJ99.png" alt="enter image description here" /></a></p>
  <p>Here is the function where I do an axios call in my frontend. The error should occur when actually creating the new user which is caught on the last catch block when calling the personService object:</p>
  <pre><code>     const personObj = {
        name: newName,
        number: newPhone
      }
  
      //Updating database and states
      phoneService
        .create(personObj)
        .then(person =&gt; {
          setPersons(persons.concat(person))
  
          //Filter
          setNewPhone(&quot;&quot;)
          setNewName(&quot;&quot;)
        }).catch(error =&gt; {
  
          setMessage(
            error.response.data
          )
          setMessageType(&quot;phone-error-add&quot;)
          console.log(error.response.data)
          return
        })
  
      setMessage(
        `Added ${personObj.name}`
      )
      setMessageType(&quot;phone-added&quot;)
  
      setTimeout(() =&gt; {
        setMessage(null)
      }, 2000)
  
    }
  </code></pre>
  <p>Here is the Axios PhoneService file:</p>
  <pre><code>import axios from 'axios'
  const baseUrl = '/api/persons'
  
  const getAll = () =&gt; {
    const request =  axios.get(baseUrl)
    return request.then(response =&gt; response.data)
  }
  
  const create = newObject =&gt; {
    
      const request = axios.post(baseUrl, newObject)
      return request.then(response =&gt; response.data)
  }
  
  const update = (id, newObject) =&gt; {
      const request = axios.put(`${baseUrl}/${id}`, newObject)
      return request.then(response =&gt; response.data)
  }
  
  const deleteData = id =&gt; {
      const request = axios.delete(`${baseUrl}/${id}`)
      return request
  }
  
  
  export default { 
    getAll, 
    create, 
    update,
    deleteData
  }
  </code></pre>
  <p>Here is the post function being called in the backend</p>
  <pre><code>app.post('/api/persons', (request, response, next) =&gt; {
  
      const body = request.body
  
      if (!body.name || !body.number) {
          return response.status(400).json({ error: 'Name or phone number is missing' })
      }
  
      const person = new Person({
          name: body.name,
          number: body.number,
      })
  
      person.save().then(savedPerson =&gt; {
          response.json(savedPerson)
      })
      .catch(error =&gt; next(error))
      // console.log(process.stdout)
  })
  </code></pre>
  <p>Here is the error handling middleware in the backend which outputs the error in the 2nd image:</p>
  <pre><code>const errorHandler = (error, request, response, next) =&gt; {
      console.error(error.message)
  
      if (error.name === 'CastError') {
          return response.status(400).send({ error: 'malformatted id' })
      } else if (error.name === &quot;ValidationError&quot;) {
          return response.status(400).json({ error: error.message })
      }
  
      next(error)
  }
  
  // this has to be the last loaded middleware.
  app.use(errorHandler)
  </code></pre>