JokerMartini
JokerMartini

Reputation: 6147

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]}}' }
...

Upvotes: 0

Views: 1019

Answers (2)

moomoolive
moomoolive

Reputation: 162

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))

Upvotes: 1

Casper Kuethe
Casper Kuethe

Reputation: 1130

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],
  }
}

Upvotes: 1

Related Questions