Search code examples
jsonnode.jsreactjsaxiosexpress-router

Malformed json in request body


In our react application, we are posting json string entered in a text area, to an express router function. In the client we are using axios to post the data to express router.

We do receive the data in the express router function like :

const reqData = request.body

But when we inspect the data which is received in the router function, the json we are passing is wrapped with another curly braces:

{{"user":"emp","comapany":"acme"}}

The outer braces are added automatically it seems and because of this, JSON.parse is failing.

Is there a way to avoid this?


Solution

  • I believe the issue is that you're using a reference to the entire req.body, when you usually want to pull off specific properties.

    When posting from the client, use a named key:

    axios.post(`url`, {
      namedKey: {      // -> call it something suitable to your scenario
        user: 'emp',
        company: 'acme'
      }
    })
    

    In your express router, desctructure from the same name:

    const { namedKey } = request.body
    

    This could also be solved by pulling off the properties one-by-one:

    client:

    axios.post('url', {
      user: 'emp',    // user key
      company: 'acme' // company key
    })
    

    express router:

    const { user, company } = req.body
    

    It really depends how you want to organize it.