'Error when Posting Data with Axios - MERN Stack

I'm trying to test validation for my model, specifically if a name variable is of a certain length. I have a front-end setup at http://localhost:3000/ with React + axios and a backend setup with express + node.

I've set a proxy in my frontend's package,json file to include "proxy": "http://localhost:3001" and made sure that my backend includes CORS policy enabled:

const app = express()
const cors = require('cors')
app.use(cors())

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.

Front end error: enter image description here

Backend output (fine): enter image description here

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:

     const personObj = {
      name: newName,
      number: newPhone
    }

    //Updating database and states
    phoneService
      .create(personObj)
      .then(person => {
        setPersons(persons.concat(person))

        //Filter
        setNewPhone("")
        setNewName("")
      }).catch(error => {

        setMessage(
          error.response.data
        )
        setMessageType("phone-error-add")
        console.log(error.response.data)
        return
      })

    setMessage(
      `Added ${personObj.name}`
    )
    setMessageType("phone-added")

    setTimeout(() => {
      setMessage(null)
    }, 2000)

  }

Here is the Axios PhoneService file:

import axios from 'axios'
const baseUrl = '/api/persons'

const getAll = () => {
  const request =  axios.get(baseUrl)
  return request.then(response => response.data)
}

const create = newObject => {
  
    const request = axios.post(baseUrl, newObject)
    return request.then(response => response.data)
}

const update = (id, newObject) => {
    const request = axios.put(`${baseUrl}/${id}`, newObject)
    return request.then(response => response.data)
}

const deleteData = id => {
    const request = axios.delete(`${baseUrl}/${id}`)
    return request
}


export default { 
  getAll, 
  create, 
  update,
  deleteData
}

Here is the post function being called in the backend

app.post('/api/persons', (request, response, next) => {

    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 => {
        response.json(savedPerson)
    })
    .catch(error => next(error))
    // console.log(process.stdout)
})

Here is the error handling middleware in the backend which outputs the error in the 2nd image:

const errorHandler = (error, request, response, next) => {
    console.error(error.message)

    if (error.name === 'CastError') {
        return response.status(400).send({ error: 'malformatted id' })
    } else if (error.name === "ValidationError") {
        return response.status(400).json({ error: error.message })
    }

    next(error)
}

// this has to be the last loaded middleware.
app.use(errorHandler)


Solution 1:[1]

You cannot render an Object in react. Let's say the response from the server is something like

res = {error: "error message"}

It is not allowed in react to just render

<div>{res}</div>

You have to render

<div>{res.error}</div>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Phil