Amirrossein Sadeghi
Amirrossein Sadeghi

Reputation: 59

Send nested json data with get method using axios

I am trying to send a nested json data with get method using axios, but the problem is that the backend considers the children as a string.

const TOKEN = "token"
const config = {
    headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json',
        'Authorization': TOKEN,
    },
    data: {},
    params: {
        "page_id": 1,
        "filter": {
            "search": "name"
        }
    }
};
axios.get("http://localhost/api/pages", config)

What I get if I want to print filter in backend:

"{"search": "name"}"

Upvotes: 2

Views: 2250

Answers (3)

Ahmad
Ahmad

Reputation: 106

You may have two options:

1- The first option is to decode the string you receive to json.

e.g.

---json_decode() in php

--- JSONObject() in java

--- JSON.parse() in nodejs

or any other method depending on your backend language...

2- The second option is to send your object in this format:

params: {
    "page_id": 1,
    "filter[search]": "name"
}

And pay attention not to put search in quotes!

Upvotes: 8

Jon
Jon

Reputation: 166

Do a JSON.parse() of your Request.query.filter. Note that Request should be the request variable in your backend.

Upvotes: 0

technophyle
technophyle

Reputation: 9149

You can use req.query on the server side:

function get(req, res, next) {
  const { filter } = req.query;
  console.log(filter);
  ...
}

Upvotes: 0

Related Questions