简体   繁体   中英

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"}"

You may have two options:

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

eg

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

You can use req.query on the server side:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM