'How to send nested params to axios and receive on server

How can i send a nested obj of params to axios and receive them on the server side?

const params = JSON.stringify({
  sizes: {
    thumb: [400, 400],
    banner: [1280, 400],
  },
});
const res = await api({
  method: "POST",
  url: "http://localhost:3000/v1/api/create",
  params: params,
});

On the express server i have

create.js

module.exports = async function (req, res) {
...
console.log(req.query)
console.log(JSON.parse(req.query))
}

I get errors though

{ '0': '{"sizes":{"thumb":[400,400],"banner":[1280,400]}}' }
SyntaxError: Unexpected token o in JSON at position 1
    at JSON.parse (<anonymous>)

Am i passing them or receiving them incorrectly?

console print of req.query

...
{ '0': '{"sizes":{"thumb":[400,400],"banner":[1280,400]}}' }
...


Solution 1:[1]

What I think is happening is that your frontend and server are serializing and de-serializing nested queries differently.

Using the same serialization/de-serialzation function will solve the problem.

Here's an example with the "qs" library:

Frontend:

const qs = require('qs')

// don't stringify it, let the library do it for you
const params = {
  sizes: {
    thumb: [400, 400],
    banner: [1280, 400],
  },
};
const res = await api({
  method: "POST",
  url: "http://localhost:3000/v1/api/create",
  params: params,
  paramsSerializer: qs.stringify
})

Server:

const express = require('express')
const qs = require('qs')

// be sure to define this first
app.set('query parser', str => qs.parse(str))

// then define your routes
app.get("/", (req, res) => console.log(req.query))

Solution 2:[2]

It looks like req.query is already an object, that is why JSON.parse fails. The '0' property of req.query is your stringified object. So that is the part you want to parse.

let object = JSON.parse(req.query['0']);

Now object will be

{
  sizes: {
    thumb: [400, 400],
    banner: [1280, 400],
  }
}

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 moomoolive
Solution 2 Casper Kuethe